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-controller.php

    r42343 r43087  
    201201        $this->assertEquals( 'a', $args['somedefault']['default'] );
    202202    }
     203
     204    public function test_get_fields_for_response() {
     205        $controller = new WP_REST_Test_Controller();
     206        $request    = new WP_REST_Request( 'GET', '/wp/v2/testroute' );
     207        $fields     = $controller->get_fields_for_response( $request );
     208        $this->assertEquals( array(
     209            'somestring',
     210            'someinteger',
     211            'someboolean',
     212            'someurl',
     213            'somedate',
     214            'someemail',
     215            'someenum',
     216            'someargoptions',
     217            'somedefault',
     218        ), $fields );
     219        $request->set_param( '_fields', 'somestring,someinteger' );
     220        $fields = $controller->get_fields_for_response( $request );
     221        $this->assertEquals( array(
     222            'somestring',
     223            'someinteger',
     224        ), $fields );
     225    }
    203226}
Note: See TracChangeset for help on using the changeset viewer.