Make WordPress Core


Ignore:
Timestamp:
07/13/2018 06:50:51 AM (6 years ago)
Author:
pento
Message:

REST API: Filter responses based on the _fields parameter, before data is processed.

Historically, the REST API would generate the entire response object, including running expensive filters, then it would apply the _fields parameter, discarding the fields that weren't specificed.

This change causes _fields to be applied earlier, so that only requested fields are processed.

Merges [43087] to the 4.9 branch.

Props danielbachhuber.
See #43874.

Location:
branches/4.9
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/4.9

  • branches/4.9/tests/phpunit/tests/rest-api/rest-pages-controller.php

    r41228 r43445  
    334334    public function test_prepare_item() {
    335335
     336    }
     337
     338    public function test_prepare_item_limit_fields() {
     339        wp_set_current_user( self::$editor_id );
     340        $page_id  = $this->factory->post->create(
     341            array(
     342                'post_status' => 'publish',
     343                'post_type'   => 'page',
     344            )
     345        );
     346        $endpoint = new WP_REST_Posts_Controller( 'page' );
     347        $request  = new WP_REST_Request( 'GET', sprintf( '/wp/v2/pages/%d', $page_id ) );
     348        $request->set_param( 'context', 'edit' );
     349        $request->set_param( '_fields', 'id,slug' );
     350        $obj      = get_post( $page_id );
     351        $response = $endpoint->prepare_item_for_response( $obj, $request );
     352        $this->assertEquals( array(
     353            'id',
     354            'slug',
     355        ), array_keys( $response->get_data() ) );
    336356    }
    337357
Note: See TracChangeset for help on using the changeset viewer.