WordPress.org

Make WordPress Core


Ignore:
Timestamp:
05/02/2018 01:24:30 AM (3 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.

Props danielbachhuber.
See #43874.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/rest-api/rest-pages-controller.php

    r42724 r43087  
    450450    public function test_prepare_item() {
    451451
     452    }
     453
     454    public function test_prepare_item_limit_fields() {
     455        wp_set_current_user( self::$editor_id );
     456        $page_id  = $this->factory->post->create(
     457            array(
     458                'post_status' => 'publish',
     459                'post_type'   => 'page',
     460            )
     461        );
     462        $endpoint = new WP_REST_Posts_Controller( 'page' );
     463        $request  = new WP_REST_Request( 'GET', sprintf( '/wp/v2/pages/%d', $page_id ) );
     464        $request->set_param( 'context', 'edit' );
     465        $request->set_param( '_fields', 'id,slug' );
     466        $obj      = get_post( $page_id );
     467        $response = $endpoint->prepare_item_for_response( $obj, $request );
     468        $this->assertEquals( array(
     469            'id',
     470            'slug',
     471        ), array_keys( $response->get_data() ) );
    452472    }
    453473
Note: See TracChangeset for help on using the changeset viewer.