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.



git-svn-id: https://develop.svn.wordpress.org/trunk@43087 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Gary Pendergast
2018-05-02 01:24:30 +00:00
parent 1a4e28818f
commit 4ac3f4c13a
22 changed files with 526 additions and 167 deletions

View File

@@ -1178,6 +1178,27 @@ class WP_Test_REST_Attachments_Controller extends WP_Test_REST_Post_Type_Control
$this->check_post_data( $attachment, $data, 'embed', $response->get_links() );
}
public function test_prepare_item_limit_fields() {
$attachment_id = $this->factory->attachment->create_object(
$this->test_file, 0, array(
'post_mime_type' => 'image/jpeg',
'post_excerpt' => 'A sample caption',
'post_author' => self::$editor_id,
)
);
wp_set_current_user( self::$editor_id );
$endpoint = new WP_REST_Attachments_Controller( 'post' );
$request = new WP_REST_Request( 'GET', sprintf( '/wp/v2/media/%d', $attachment_id ) );
$request->set_param( 'context', 'edit' );
$request->set_param( '_fields', 'id,slug' );
$obj = get_post( $attachment_id );
$response = $endpoint->prepare_item_for_response( $obj, $request );
$this->assertEquals( array(
'id',
'slug',
), array_keys( $response->get_data() ) );
}
public function test_get_item_schema() {
$request = new WP_REST_Request( 'OPTIONS', '/wp/v2/media' );
$response = rest_get_server()->dispatch( $request );