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

    r42770 r43087  
    11771177        $this->check_post_data( $attachment, $data, 'view', $response->get_links() );
    11781178        $this->check_post_data( $attachment, $data, 'embed', $response->get_links() );
     1179    }
     1180
     1181    public function test_prepare_item_limit_fields() {
     1182        $attachment_id = $this->factory->attachment->create_object(
     1183            $this->test_file, 0, array(
     1184                'post_mime_type' => 'image/jpeg',
     1185                'post_excerpt'   => 'A sample caption',
     1186                'post_author'    => self::$editor_id,
     1187            )
     1188        );
     1189        wp_set_current_user( self::$editor_id );
     1190        $endpoint = new WP_REST_Attachments_Controller( 'post' );
     1191        $request  = new WP_REST_Request( 'GET', sprintf( '/wp/v2/media/%d', $attachment_id ) );
     1192        $request->set_param( 'context', 'edit' );
     1193        $request->set_param( '_fields', 'id,slug' );
     1194        $obj      = get_post( $attachment_id );
     1195        $response = $endpoint->prepare_item_for_response( $obj, $request );
     1196        $this->assertEquals( array(
     1197            'id',
     1198            'slug',
     1199        ), array_keys( $response->get_data() ) );
    11791200    }
    11801201
Note: See TracChangeset for help on using the changeset viewer.