Make WordPress Core

Changeset 53217


Ignore:
Timestamp:
04/19/2022 02:38:16 PM (2 years ago)
Author:
gziolo
Message:

REST API: Respect _fields query arg in preloaded requests

Ensures that preloaded request can include a _fields query param that asks that only selected response fields are returned.

Props jsnajdr, timothyblynjacobs.
Fixes #55213.
See #55567.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api.php

    r53152 r53217  
    28692869    if ( 200 === $response->status ) {
    28702870        $server = rest_get_server();
     2871        /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
     2872        $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $server, $request );
    28712873        $embed  = $request->has_param( '_embed' ) ? rest_parse_embed_param( $request['_embed'] ) : false;
    28722874        $data   = (array) $server->response_to_data( $response, $embed );
    28732875
    28742876        if ( 'OPTIONS' === $method ) {
    2875             $response = rest_send_allow_header( $response, $server, $request );
    2876 
    28772877            $memo[ $method ][ $path ] = array(
    28782878                'body'    => $data,
  • trunk/tests/phpunit/tests/rest-api.php

    r52010 r53217  
    24912491        );
    24922492    }
     2493
     2494    /**
     2495     * @ticket 55213
     2496     */
     2497    public function test_rest_preload_api_request_fields() {
     2498        $preload_paths = array(
     2499            '/',
     2500            '/?_fields=description',
     2501        );
     2502
     2503        $preload_data = array_reduce(
     2504            $preload_paths,
     2505            'rest_preload_api_request',
     2506            array()
     2507        );
     2508
     2509        $this->assertSame( array_keys( $preload_data ), array( '/', '/?_fields=description' ) );
     2510
     2511        // Unfiltered request has all fields
     2512        $this->assertArrayHasKey( 'description', $preload_data['/']['body'] );
     2513        $this->assertArrayHasKey( 'routes', $preload_data['/']['body'] );
     2514
     2515        // Filtered request only has the desired fields + links
     2516        $this->assertSame(
     2517            array_keys( $preload_data['/?_fields=description']['body'] ),
     2518            array( 'description', '_links' )
     2519        );
     2520    }
    24932521}
Note: See TracChangeset for help on using the changeset viewer.