Skip to content

Commit

Permalink
Add the middlewares API
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad committed Jun 1, 2018
1 parent 3754c8e commit 269e45d
Show file tree
Hide file tree
Showing 23 changed files with 296 additions and 234 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ module.exports = {
'jest/globals': true,
},
globals: {
wpApiSettings: true,
wpApiSchema: true,
},
plugins: [
'jest',
Expand Down
4 changes: 2 additions & 2 deletions components/code-editor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function loadScript() {
}

const script = document.createElement( 'script' );
script.src = `${ wpApiSettings.schema.url }/wp-admin/load-scripts.php?load=${ handles.join( ',' ) }`;
script.src = `${ wpApiSchema.url }/wp-admin/load-scripts.php?load=${ handles.join( ',' ) }`;
script.onload = resolve;
script.onerror = reject;

Expand All @@ -35,7 +35,7 @@ function loadStyle() {

const style = document.createElement( 'link' );
style.rel = 'stylesheet';
style.href = `${ wpApiSettings.schema.url }/wp-admin/load-styles.php?load=${ handles.join( ',' ) }`;
style.href = `${ wpApiSchema.url }/wp-admin/load-styles.php?load=${ handles.join( ',' ) }`;
style.onload = resolve;
style.onerror = reject;

Expand Down
7 changes: 6 additions & 1 deletion components/higher-order/with-api-data/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
import memoize from 'memize';
import { mapKeys } from 'lodash';

/**
* WordPress dependencies
*/
import apiRequest from '@wordpress/api-request';

export const getStablePath = memoize( ( path ) => {
const [ base, query ] = path.split( '?' );
if ( ! query ) {
Expand Down Expand Up @@ -75,7 +80,7 @@ export function getCachedResponse( request ) {
}

export function getResponseFromNetwork( request ) {
const promise = wp.apiRequest( request )
const promise = apiRequest( request )
.then( ( body, status, xhr ) => {
return {
body,
Expand Down
3 changes: 2 additions & 1 deletion core-blocks/embed/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
BlockAlignmentToolbar,
RichText,
} from '@wordpress/editor';
import apiRequest from '@wordpress/api-request';

/**
* Internal dependencies
Expand All @@ -30,7 +31,7 @@ import './editor.scss';
const HOSTS_NO_PREVIEWS = [ 'facebook.com' ];

// Caches the embed API calls, so if blocks get transformed, or deleted and added again, we don't spam the API.
const wpEmbedAPI = memoize( ( url ) => wp.apiRequest( { path: `/oembed/1.0/proxy?${ stringify( { url } ) }` } ) );
const wpEmbedAPI = memoize( ( url ) => apiRequest( { path: `/oembed/1.0/proxy?${ stringify( { url } ) }` } ) );

const matchesPatterns = ( url, patterns = [] ) => {
return patterns.some( ( pattern ) => {
Expand Down
10 changes: 0 additions & 10 deletions edit-post/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,6 @@ import store from './store';
import { initializeMetaBoxState } from './store/actions';
import Editor from './editor';

/**
* Configure heartbeat to refresh the wp-api nonce, keeping the editor
* authorization intact.
*/
window.jQuery( document ).on( 'heartbeat-tick', ( event, response ) => {
if ( response[ 'rest-nonce' ] ) {
window.wpApiSettings.nonce = response[ 'rest-nonce' ];
}
} );

/**
* Reinitializes the editor after the user chooses to reboot the editor after
* an unhandled error occurs, replacing previously mounted editor element using
Expand Down
3 changes: 2 additions & 1 deletion edit-post/store/effects.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { reduce, some } from 'lodash';
import { select, subscribe } from '@wordpress/data';
import { speak } from '@wordpress/a11y';
import { __ } from '@wordpress/i18n';
import apiRequest from '@wordpress/api-request';

/**
* Internal dependencies
Expand Down Expand Up @@ -98,7 +99,7 @@ const effects = {
additionalData.forEach( ( [ key, value ] ) => formData.append( key, value ) );

// Save the metaboxes
wp.apiRequest( {
apiRequest( {
url: window._wpMetaBoxUrl,
method: 'POST',
processData: false,
Expand Down
7 changes: 6 additions & 1 deletion editor/components/autocompleters/user.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/**
* WordPress dependencies
*/
import apiRequest from '@wordpress/api-request';

/**
* A user mentions completer.
*
Expand All @@ -12,7 +17,7 @@ export default {
if ( search ) {
payload = '?search=' + encodeURIComponent( search );
}
return wp.apiRequest( { path: '/wp/v2/users' + payload } );
return apiRequest( { path: '/wp/v2/users' + payload } );
},
isDebounced: true,
getOptionKeywords( user ) {
Expand Down
7 changes: 4 additions & 3 deletions editor/components/post-taxonomies/flat-term-selector.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { __, _x, sprintf } from '@wordpress/i18n';
import { Component, compose } from '@wordpress/element';
import { FormTokenField, withAPIData } from '@wordpress/components';
import { withSelect, withDispatch } from '@wordpress/data';
import apiRequest from '@wordpress/api-request';

/**
* Module constants
Expand Down Expand Up @@ -75,7 +76,7 @@ class FlatTermSelector extends Component {
fetchTerms( params = {} ) {
const query = { ...DEFAULT_QUERY, ...params };
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
const request = wp.apiRequest( { path: `/wp/v2/${ basePath }?${ stringify( query ) }` } );
const request = apiRequest( { path: `/wp/v2/${ basePath }?${ stringify( query ) }` } );
request.then( ( terms ) => {
this.setState( ( state ) => ( {
availableTerms: state.availableTerms.concat(
Expand Down Expand Up @@ -106,15 +107,15 @@ class FlatTermSelector extends Component {
return new Promise( ( resolve, reject ) => {
// Tries to create a term or fetch it if it already exists
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
wp.apiRequest( {
apiRequest( {
path: `/wp/v2/${ basePath }`,
method: 'POST',
data: { name: termName },
} ).then( resolve, ( xhr ) => {
const errorCode = xhr.responseJSON && xhr.responseJSON.code;
if ( errorCode === 'term_exists' ) {
// search the new category created since last fetch
this.addRequest = wp.apiRequest( {
this.addRequest = apiRequest( {
path: `/wp/v2/${ basePath }?${ stringify( { ...DEFAULT_QUERY, search: termName } ) }`,
} );
return this.addRequest.then( ( searchResult ) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Component, compose } from '@wordpress/element';
import { TreeSelect, withAPIData, withInstanceId, withSpokenMessages, Button } from '@wordpress/components';
import { buildTermsTree } from '@wordpress/utils';
import { withSelect, withDispatch } from '@wordpress/data';
import apiRequest from '@wordpress/api-request';

/**
* Module Constants
Expand Down Expand Up @@ -103,7 +104,7 @@ class HierarchicalTermSelector extends Component {
} );
// Tries to create a term or fetch it if it already exists
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
this.addRequest = wp.apiRequest( {
this.addRequest = apiRequest( {
path: `/wp/v2/${ basePath }`,
method: 'POST',
data: {
Expand All @@ -116,7 +117,7 @@ class HierarchicalTermSelector extends Component {
const errorCode = xhr.responseJSON && xhr.responseJSON.code;
if ( errorCode === 'term_exists' ) {
// search the new category created since last fetch
this.addRequest = wp.apiRequest( {
this.addRequest = apiRequest( {
path: `/wp/v2/${ basePath }?${ stringify( { ...DEFAULT_QUERY, parent: formParent || 0, search: formName } ) }`,
} );
return this.addRequest.then( ( searchResult ) => {
Expand Down Expand Up @@ -161,7 +162,7 @@ class HierarchicalTermSelector extends Component {

componentDidMount() {
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
this.fetchRequest = wp.apiRequest( { path: `/wp/v2/${ basePath }?${ stringify( DEFAULT_QUERY ) }` } );
this.fetchRequest = apiRequest( { path: `/wp/v2/${ basePath }?${ stringify( DEFAULT_QUERY ) }` } );
this.fetchRequest.then(
( terms ) => { // resolve
const availableTermsTree = buildTermsTree( terms );
Expand Down
2 changes: 1 addition & 1 deletion editor/components/provider/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class EditorProvider extends Component {
[
APIProvider,
{
...wpApiSettings,
schema: wpApiSchema,
...pick( wp.api, [
'postTypeRestBaseMapping',
'taxonomyRestBaseMapping',
Expand Down
3 changes: 2 additions & 1 deletion editor/components/url-input/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { __, sprintf, _n } from '@wordpress/i18n';
import { Component, Fragment } from '@wordpress/element';
import { keycodes, decodeEntities } from '@wordpress/utils';
import { Spinner, withInstanceId, withSpokenMessages, Popover } from '@wordpress/components';
import apiRequest from '@wordpress/api-request';

const { UP, DOWN, ENTER } = keycodes;

Expand Down Expand Up @@ -68,7 +69,7 @@ class UrlInput extends Component {
selectedSuggestion: null,
loading: true,
} );
this.suggestionsRequest = wp.apiRequest( {
this.suggestionsRequest = apiRequest( {
path: `/wp/v2/posts?${ stringify( {
search: value,
per_page: 20,
Expand Down
17 changes: 9 additions & 8 deletions editor/store/effects.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
} from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { speak } from '@wordpress/a11y';
import apiRequest from '@wordpress/api-request';

/**
* Internal dependencies
Expand Down Expand Up @@ -120,7 +121,7 @@ export default {
if ( isAutosave ) {
toSend.parent = post.id;

request = wp.apiRequest( {
request = apiRequest( {
path: `/wp/v2/${ basePath }/${ post.id }/autosaves`,
method: 'POST',
data: toSend,
Expand All @@ -134,7 +135,7 @@ export default {

dispatch( removeNotice( SAVE_POST_NOTICE_ID ) );

request = wp.apiRequest( {
request = apiRequest( {
path: `/wp/v2/${ basePath }/${ post.id }`,
method: 'PUT',
data: toSend,
Expand Down Expand Up @@ -243,7 +244,7 @@ export default {
const { postId } = action;
const basePath = wp.api.getPostTypeRoute( getCurrentPostType( getState() ) );
dispatch( removeNotice( TRASH_POST_NOTICE_ID ) );
wp.apiRequest( { path: `/wp/v2/${ basePath }/${ postId }`, method: 'DELETE' } ).then(
apiRequest( { path: `/wp/v2/${ basePath }/${ postId }`, method: 'DELETE' } ).then(
() => {
dispatch( {
...action,
Expand Down Expand Up @@ -286,7 +287,7 @@ export default {
context: 'edit',
};

wp.apiRequest( { path: `/wp/v2/${ basePath }/${ post.id }`, data } ).then(
apiRequest( { path: `/wp/v2/${ basePath }/${ post.id }`, data } ).then(
( newPost ) => {
dispatch( resetPost( newPost ) );
}
Expand Down Expand Up @@ -413,9 +414,9 @@ export default {

let result;
if ( id ) {
result = wp.apiRequest( { path: `/wp/v2/${ basePath }/${ id }` } );
result = apiRequest( { path: `/wp/v2/${ basePath }/${ id }` } );
} else {
result = wp.apiRequest( { path: `/wp/v2/${ basePath }?per_page=-1` } );
result = apiRequest( { path: `/wp/v2/${ basePath }?per_page=-1` } );
}

result.then(
Expand Down Expand Up @@ -468,7 +469,7 @@ export default {
const path = isTemporary ? `/wp/v2/${ basePath }` : `/wp/v2/${ basePath }/${ id }`;
const method = isTemporary ? 'POST' : 'PUT';

wp.apiRequest( { path, data, method } ).then(
apiRequest( { path, data, method } ).then(
( updatedSharedBlock ) => {
dispatch( {
type: 'SAVE_SHARED_BLOCK_SUCCESS',
Expand Down Expand Up @@ -524,7 +525,7 @@ export default {
sharedBlock.uid,
] ) );

wp.apiRequest( { path: `/wp/v2/${ basePath }/${ id }`, method: 'DELETE' } ).then(
apiRequest( { path: `/wp/v2/${ basePath }/${ id }`, method: 'DELETE' } ).then(
() => {
dispatch( {
type: 'DELETE_SHARED_BLOCK_SUCCESS',
Expand Down
35 changes: 25 additions & 10 deletions lib/client-assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,23 @@ function gutenberg_register_scripts_and_styles() {
filemtime( gutenberg_dir_path() . 'build/api-request/index.js' ),
true
);
wp_localize_script( 'wp-api-request', 'wpApiSettings', array(
'root' => esc_url_raw( get_rest_url() ),
'nonce' => ( wp_installing() && ! is_multisite() ) ? '' : wp_create_nonce( 'wp_rest' ),
'versionString' => 'wp/v2/',
) );
wp_add_inline_script(
'wp-api-request',
sprintf(
'wp.apiRequest.use( wp.apiRequest.createNonceMiddleware( "%s" ) );',
( wp_installing() && ! is_multisite() ) ? '' : wp_create_nonce( 'wp_rest' )
),
'after'
);
wp_add_inline_script(
'wp-api-request',
sprintf(
'wp.apiRequest.use( wp.apiRequest.createRootURLMiddleware( "%s" ) );',
esc_url_raw( get_rest_url() )
),
'after'
);

wp_register_script(
'wp-deprecated',
gutenberg_url( 'build/deprecated/index.js' ),
Expand Down Expand Up @@ -166,7 +178,7 @@ function gutenberg_register_scripts_and_styles() {
wp_register_script(
'wp-utils',
gutenberg_url( 'build/utils/index.js' ),
array( 'lodash', 'wp-blob', 'wp-deprecated', 'wp-dom' ),
array( 'lodash', 'wp-blob', 'wp-deprecated', 'wp-dom', 'wp-api-request' ),
filemtime( gutenberg_dir_path() . 'build/utils/index.js' ),
true
);
Expand Down Expand Up @@ -267,6 +279,7 @@ function gutenberg_register_scripts_and_styles() {
'wp-i18n',
'wp-utils',
'wp-viewport',
'wp-api-request',
),
filemtime( gutenberg_dir_path() . 'build/core-blocks/index.js' ),
true
Expand Down Expand Up @@ -350,6 +363,7 @@ function gutenberg_register_scripts_and_styles() {
'postbox',
'wp-a11y',
'wp-api',
'wp-api-request',
'wp-blob',
'wp-blocks',
'wp-components',
Expand Down Expand Up @@ -380,6 +394,7 @@ function gutenberg_register_scripts_and_styles() {
'media-models',
'media-views',
'wp-a11y',
'wp-api-request',
'wp-components',
'wp-core-blocks',
'wp-date',
Expand Down Expand Up @@ -759,7 +774,7 @@ function gutenberg_extend_wp_api_backbone_client() {
$schema_response = rest_do_request( new WP_REST_Request( 'GET', '/' ) );
if ( ! $schema_response->is_error() ) {
wp_add_inline_script( 'wp-api', sprintf(
'wpApiSettings.cacheSchema = true; wpApiSettings.schema = %s;',
'wpApiSchema = %s;',
wp_json_encode( $schema_response->get_data() )
), 'before' );
}
Expand Down Expand Up @@ -989,9 +1004,9 @@ function gutenberg_editor_scripts_and_styles( $hook ) {
);

wp_add_inline_script(
'wp-components',
sprintf( 'window._wpAPIDataPreload = %s', wp_json_encode( $preload_data ) ),
'before'
'wp-api-request',
sprintf( 'wp.apiRequest.use( wp.apiRequest.createPreloadingMiddleware( %s ) );', wp_json_encode( $preload_data ) ),
'after'
);

// Initialize the post data.
Expand Down
Loading

0 comments on commit 269e45d

Please sign in to comment.