Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Framework: Preload common API data #2501

Merged
merged 2 commits into from
Aug 29, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions components/higher-order/with-api-data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,10 @@ export default ( mapPropsToData ) => ( WrappedComponent ) => {
[ this.getPendingKey( method ) ]: true,
} );

request( { path, method } ).then( ( data ) => {
request( { path, method } ).then( ( response ) => {
this.setIntoDataProp( propName, {
[ this.getPendingKey( method ) ]: false,
[ this.getResponseDataKey( method ) ]: data,
[ this.getResponseDataKey( method ) ]: response.body,
} );
} ).catch( ( error ) => {
this.setIntoDataProp( propName, {
Expand Down
45 changes: 40 additions & 5 deletions components/higher-order/with-api-data/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
* External dependencies
*/
import memoize from 'memize';

export const cache = {};
import { mapKeys } from 'lodash';

export const getStablePath = memoize( ( path ) => {
const [ base, query ] = path.split( '?' );
Expand All @@ -30,17 +29,53 @@ export const getStablePath = memoize( ( path ) => {
// 'a=5&b=1&c=2'
} );

/**
* Response cache of path to response (object of data, headers arrays).
* Optionally populated from window global for preloading.
*
* @type {Object}
*/
export const cache = mapKeys(
window._wpAPIDataPreload,
( value, key ) => getStablePath( key )
);

/**
* Given an XMLHttpRequest object, returns an array of header tuples.
*
* @see https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
*
* @param {XMLHttpRequest} xhr XMLHttpRequest object
* @return {Array[]} Array of header tuples
*/
export function getResponseHeaders( xhr ) {
return xhr.getAllResponseHeaders().trim()
// 'date: Tue, 22 Aug 2017 18:45:28 GMT↵server: nginx'

.split( '\u000d\u000a' )
// [ 'date: Tue, 22 Aug 2017 18:45:28 GMT', 'server: nginx' ]

.map( ( entry ) => entry.split( '\u003a\u0020' ) );
// [ [ 'date', 'Tue, 22 Aug 2017 18:45:28 GMT' ], [ 'server', 'nginx' ] ]
}

export function getResponseFromCache( request ) {
const response = cache[ getStablePath( request.path ) ];
return Promise.resolve( response );
}

export function getResponseFromNetwork( request ) {
const promise = wp.apiRequest( request ).promise();
const promise = wp.apiRequest( request )
.then( ( body, status, xhr ) => {
return {
body,
headers: getResponseHeaders( xhr ),
};
} );

if ( isRequestMethod( request, 'GET' ) ) {
promise.then( ( data ) => {
cache[ getStablePath( request.path ) ] = data;
promise.then( ( response ) => {
cache[ getStablePath( request.path ) ] = response;
} );
}

Expand Down
4 changes: 3 additions & 1 deletion components/higher-order/with-api-data/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import { identity, fromPairs } from 'lodash';
*/
import withAPIData from '../';

jest.mock( '../request', () => jest.fn( () => Promise.resolve( {} ) ) );
jest.mock( '../request', () => jest.fn( () => Promise.resolve( {
body: {},
} ) ) );

describe( 'withAPIData()', () => {
const schema = {
Expand Down
44 changes: 37 additions & 7 deletions components/higher-order/with-api-data/test/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,26 @@
import request, {
cache,
getStablePath,
getResponseHeaders,
getResponseFromCache,
getResponseFromNetwork,
isRequestMethod,
} from '../request';

describe( 'request', () => {
const actualResponse = {};
const actualResponse = {
body: {},
headers: [
[ 'connection', 'Keep-Alive' ],
[ 'content-type', 'text/plain; charset=utf-8' ],
],
};
const xhr = {
getAllResponseHeaders: () => (
'connection\u003a\u0020Keep-Alive\u000d\u000a' +
'content-type\u003a\u0020text/plain; charset=utf-8'
),
};

let wpApiRequest;
beforeEach( () => {
Expand All @@ -21,22 +34,39 @@ describe( 'request', () => {

wpApiRequest = wp.apiRequest;
wp.apiRequest = jest.fn( () => ( {
promise: () => Promise.resolve( actualResponse ),
// jQuery.Deferred aren't true promises, particularly in their
// treatment of resolved arguments. $.ajax will spread resolved
// arguments, but this is not valid for Promise (only single).
// Instead, we emulate by invoking the callback manually.
then: ( callback ) => Promise.resolve( callback(
actualResponse.body,
'success',
xhr
) ),
} ) );
} );

afterEach( () => {
wp.apiRequest = wpApiRequest;
} );

describe( 'getResponseHeaders()', () =>{
it( 'returns tuples of array headers', () => {
expect( getResponseHeaders( xhr ) ).toEqual( [
[ 'connection', 'Keep-Alive' ],
[ 'content-type', 'text/plain; charset=utf-8' ],
] );
} );
} );

describe( 'getResponseFromCache()', () => {
it( 'returns response from cache', () => {
cache[ getStablePath( '/wp?c=5&a=5&b=5' ) ] = actualResponse;
const awaitResponse = getResponseFromCache( {
path: '/wp?b=5&c=5&a=5',
} );

expect( awaitResponse ).resolves.toBe( actualResponse );
expect( awaitResponse ).resolves.toEqual( actualResponse );
} );
} );

Expand All @@ -48,7 +78,7 @@ describe( 'request', () => {

return awaitResponse.then( ( data ) => {
expect( wp.apiRequest ).toHaveBeenCalled();
expect( data ).toBe( actualResponse );
expect( data ).toEqual( actualResponse );
} );
} );
} );
Expand Down Expand Up @@ -88,7 +118,7 @@ describe( 'request', () => {

return awaitResponse.then( ( data ) => {
expect( wp.apiRequest ).not.toHaveBeenCalled();
expect( data ).toBe( actualResponse );
expect( data ).toEqual( actualResponse );
} );
} );

Expand All @@ -101,7 +131,7 @@ describe( 'request', () => {

return awaitResponse.then( ( data ) => {
expect( wp.apiRequest ).toHaveBeenCalled();
expect( data ).toBe( actualResponse );
expect( data ).toEqual( actualResponse );
} );
} );

Expand All @@ -113,7 +143,7 @@ describe( 'request', () => {

return awaitResponse.then( ( data ) => {
expect( wp.apiRequest ).toHaveBeenCalled();
expect( data ).toBe( actualResponse );
expect( data ).toEqual( actualResponse );
} );
} );
} );
Expand Down
91 changes: 90 additions & 1 deletion lib/client-assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,42 @@ function gutenberg_register_scripts_and_styles() {
}
add_action( 'init', 'gutenberg_register_scripts_and_styles' );

/**
* Append result of internal request to REST API for purpose of preloading
* data to be attached to the page. Expected to be called in the context of
* `array_reduce`.
*
* @param array $memo Reduce accumulator.
* @param string $path REST API path to preload.
* @return array Modified reduce accumulator.
*/
function gutenberg_preload_api_request( $memo, $path ) {
if ( empty( $path ) ) {
return $memo;
}

$path_parts = parse_url( $path );
if ( false === $path_parts ) {
return $memo;
}

$request = new WP_REST_Request( 'GET', $path_parts['path'] );
if ( ! empty( $path_parts['query'] ) ) {
parse_str( $path_parts['query'], $query_params );
$request->set_query_params( $query_params );
}

$response = rest_do_request( $request );
if ( 200 === $response->status ) {
$memo[ $path ] = array(
'body' => $response->data,
'headers' => $response->headers,
);
}

return $memo;
}

/**
* Registers vendor JavaScript files to be used as dependencies of the editor
* and plugins.
Expand Down Expand Up @@ -286,6 +322,40 @@ function gutenberg_vendor_script_filename( $src ) {
. $filename_pieces['extension'];
}

/**
* Given a REST data response with links, returns the href value of a specified
* link relation with optional context.
*
* @since 0.10.0
*
* @param array $data REST response data.
* @param string $link Link relation.
* @param string $context Optional context to append.
* @return string Link relation URI.
*/
function gutenberg_get_rest_link( $data, $link, $context = null ) {
// Check whether a link entry with href exists.
if ( empty( $data['_links'] ) || empty( $data['_links'][ $link ] ) ||
! isset( $data['_links'][ $link ][0]['href'] ) ) {
return;
}

$href = $data['_links'][ $link ][0]['href'];

// Strip API root prefix.
$api_root = untrailingslashit( get_rest_url() );
if ( 0 === strpos( $href, $api_root ) ) {
$href = substr( $href, strlen( $api_root ) );
}

// Add optional context.
if ( ! is_null( $context ) ) {
$href = add_query_arg( 'context', $context, $href );
}

return $href;
}

/**
* Registers a vendor script from a URL, preferring a locally cached version if
* possible, or downloading it if the cached version is unavailable or
Expand Down Expand Up @@ -451,7 +521,7 @@ function gutenberg_get_post_to_edit( $post_id ) {
if ( $response->is_error() ) {
return $response->as_error();
}
return $response->get_data();
return rest_get_server()->response_to_data( $response, false );
}

/**
Expand Down Expand Up @@ -658,6 +728,25 @@ function gutenberg_editor_scripts_and_styles( $hook ) {
);
}

// Preload common data.
$preload_paths = array(
'/wp/v2/users/me?context=edit',
gutenberg_get_rest_link( $post_to_edit, 'about', 'edit' ),
);
if ( ! $is_new_post ) {
$preload_paths[] = gutenberg_get_rest_link( $post_to_edit, 'version-history' );
}
$preload_data = array_reduce(
$preload_paths,
'gutenberg_preload_api_request',
array()
);
wp_add_inline_script(
'wp-components',
sprintf( 'window._wpAPIDataPreload = %s', wp_json_encode( $preload_data ) ),
'before'
);

// Initialize the post data.
wp_add_inline_script(
'wp-editor',
Expand Down