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: Use a single way to call APIs: wp.apiRequest #5253

Merged
merged 2 commits into from
Feb 28, 2018
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
2 changes: 1 addition & 1 deletion blocks/autocompleters/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export function blockAutocompleter( { onReplace } ) {
*/
export function userAutocompleter() {
const getOptions = () => {
return ( new wp.api.collections.Users() ).fetch().then( ( users ) => {
return wp.apiRequest( { path: '/wp/v2/users' } ).then( ( users ) => {
return users.map( ( user ) => {
return {
value: user,
Expand Down
31 changes: 13 additions & 18 deletions blocks/library/embed/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
*/
import { parse } from 'url';
import { includes, kebabCase, toLower } from 'lodash';
import { stringify } from 'querystring';

/**
* WordPress dependencies
*/
import { __, sprintf } from '@wordpress/i18n';
import { Component, renderToString } from '@wordpress/element';
import { Button, Placeholder, Spinner, SandBox } from '@wordpress/components';
import { addQueryArgs } from '@wordpress/url';
import classnames from 'classnames';

/**
Expand Down Expand Up @@ -109,20 +109,15 @@ function getEmbedBlockSettings( { title, icon, category = 'embed', transforms, k
}
const { url } = this.props.attributes;
const { setAttributes } = this.props;
const apiURL = addQueryArgs( wpApiSettings.root + 'oembed/1.0/proxy', {
url: url,
_wpnonce: wpApiSettings.nonce,
} );

this.setState( { error: false, fetching: true } );
window.fetch( apiURL, {
credentials: 'include',
} ).then(
( response ) => {
if ( this.unmounting ) {
return;
}
response.json().then( ( obj ) => {
wp.apiRequest( { path: `/oembed/1.0/proxy?${ stringify( { url } ) }` } )
.then(
( obj ) => {
if ( this.unmounting ) {
return;
}

const { html, provider_name: providerName } = obj;
const providerNameSlug = kebabCase( toLower( providerName ) );
let { type } = obj;
Expand All @@ -136,13 +131,13 @@ function getEmbedBlockSettings( { title, icon, category = 'embed', transforms, k
} else if ( 'photo' === type ) {
this.setState( { html: this.getPhotoHtml( obj ), type, providerNameSlug } );
setAttributes( { type, providerNameSlug } );
} else {
this.setState( { error: true } );
}
this.setState( { fetching: false } );
} );
}
);
},
() => {
this.setState( { fetching: false, error: true } );
}
);
}

render() {
Expand Down
13 changes: 8 additions & 5 deletions blocks/url-input/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { throttle } from 'lodash';
import classnames from 'classnames';
import scrollIntoView from 'dom-scroll-into-view';
import { stringify } from 'querystringify';

/**
* WordPress dependencies
Expand Down Expand Up @@ -66,11 +67,13 @@ class UrlInput extends Component {
selectedSuggestion: null,
loading: true,
} );
this.suggestionsRequest = new wp.api.collections.Posts().fetch( { data: {
search: value,
per_page: 20,
orderby: 'relevance',
} } );
this.suggestionsRequest = wp.apiRequest( {
path: `/wp/v2/posts?${ stringify( {
search: value,
per_page: 20,
orderby: 'relevance',
} ) }`,
} );

this.suggestionsRequest
.then(
Expand Down
13 changes: 6 additions & 7 deletions edit-post/store/effects.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,14 @@ const effects = {
.concat( jQuery( '.metabox-base-form' ).serialize() )
.concat( additionalData )
.join( '&' );
const fetchOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: formData,
credentials: 'include',
};

// Save the metaboxes
window.fetch( window._wpMetaBoxUrl, fetchOptions )
wp.apiRequest( {
url: window._wpMetaBoxUrl,
method: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: formData,
} )
.then( () => store.dispatch( metaBoxUpdatesSuccess() ) );
},
};
Expand Down
41 changes: 22 additions & 19 deletions editor/components/post-taxonomies/flat-term-selector.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import { connect } from 'react-redux';
import { get, unescape as unescapeString, find, throttle, uniqBy } from 'lodash';
import { stringify } from 'querystring';

/**
* WordPress dependencies
Expand All @@ -24,7 +25,7 @@ const DEFAULT_QUERY = {
per_page: 100,
orderby: 'count',
order: 'desc',
_fields: [ 'id', 'name' ],
_fields: 'id,name',
};
const MAX_TERMS_SUGGESTIONS = 20;
const isSameTermName = ( termA, termB ) => termA.toLowerCase() === termB.toLowerCase();
Expand Down Expand Up @@ -78,8 +79,8 @@ class FlatTermSelector extends Component {

fetchTerms( params = {} ) {
const query = { ...DEFAULT_QUERY, ...params };
const Collection = wp.api.getTaxonomyCollection( this.props.slug );
const request = new Collection().fetch( { data: query } );
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
const request = wp.apiRequest( { path: `/wp/v2/${ basePath }?${ stringify( query ) }` } );
request.then( ( terms ) => {
this.setState( ( state ) => ( {
availableTerms: state.availableTerms.concat(
Expand All @@ -105,21 +106,24 @@ class FlatTermSelector extends Component {
findOrCreateTerm( termName ) {
return new Promise( ( resolve, reject ) => {
// Tries to create a term or fetch it if it already exists
const Model = wp.api.getTaxonomyModel( this.props.slug );
new Model( { name: termName } ).save()
.then( resolve, ( xhr ) => {
const errorCode = xhr.responseJSON && xhr.responseJSON.code;
if ( errorCode === 'term_exists' ) {
// search the new category created since last fetch
this.addRequest = new Model().fetch(
{ data: { ...DEFAULT_QUERY, search: termName } }
);
return this.addRequest.then( searchResult => {
resolve( find( searchResult, result => isSameTermName( result.name, termName ) ) );
}, reject );
}
reject( xhr );
} );
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
wp.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( {
path: `/wp/v2/${ basePath }?${ stringify( { ...DEFAULT_QUERY, search: termName } ) }`,
} );
return this.addRequest.then( searchResult => {
resolve( find( searchResult, result => isSameTermName( result.name, termName ) ) );
}, reject );
}
reject( xhr );
} );
} );
}

Expand Down Expand Up @@ -159,7 +163,6 @@ class FlatTermSelector extends Component {
const { label, slug, taxonomy } = this.props;
const { loading, availableTerms, selectedTerms } = this.state;
const termNames = availableTerms.map( ( term ) => term.name );

const newTermPlaceholderLabel = get(
taxonomy,
[ 'data', 'labels', 'add_new_item' ],
Expand Down
28 changes: 16 additions & 12 deletions editor/components/post-taxonomies/hierarchical-term-selector.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import { connect } from 'react-redux';
import { get, unescape as unescapeString, without, find, some } from 'lodash';
import { stringify } from 'querystring';

/**
* WordPress dependencies
Expand All @@ -25,7 +26,7 @@ const DEFAULT_QUERY = {
per_page: 100,
orderby: 'count',
order: 'desc',
_fields: [ 'id', 'name', 'parent' ],
_fields: 'id,name,parent',
};

class HierarchicalTermSelector extends Component {
Expand Down Expand Up @@ -107,19 +108,23 @@ class HierarchicalTermSelector extends Component {
adding: true,
} );
// Tries to create a term or fetch it if it already exists
const Model = wp.api.getTaxonomyModel( this.props.slug );
this.addRequest = new Model( {
name: formName,
parent: formParent ? formParent : undefined,
} ).save();
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
this.addRequest = wp.apiRequest( {
path: `/wp/v2/${ basePath }`,
method: 'POST',
data: {
name: formName,
parent: formParent ? formParent : undefined,
},
} );
this.addRequest
.then( resolve, ( xhr ) => {
const errorCode = xhr.responseJSON && xhr.responseJSON.code;
if ( errorCode === 'term_exists' ) {
// search the new category created since last fetch
this.addRequest = new Model().fetch(
{ data: { ...DEFAULT_QUERY, parent: formParent || 0, search: formName } }
);
this.addRequest = wp.apiRequest( {
path: `/wp/v2/${ basePath }?${ stringify( { ...DEFAULT_QUERY, parent: formParent || 0, search: formName } ) }`,
} );
return this.addRequest.then( searchResult => {
resolve( this.findTerm( searchResult, formParent, formName ) );
}, reject );
Expand Down Expand Up @@ -159,9 +164,8 @@ class HierarchicalTermSelector extends Component {
}

componentDidMount() {
const Collection = wp.api.getTaxonomyCollection( this.props.slug );
this.fetchRequest = new Collection()
.fetch( { data: DEFAULT_QUERY } )
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
this.fetchRequest = wp.apiRequest( { path: `/wp/v2/${ basePath }?${ stringify( DEFAULT_QUERY ) }` } )
.done( ( terms ) => {
const availableTermsTree = buildTermsTree( terms );

Expand Down
33 changes: 19 additions & 14 deletions editor/store/effects.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* External dependencies
*/
import { BEGIN, COMMIT, REVERT } from 'redux-optimist';
import { get, has, includes, map, castArray, uniqueId } from 'lodash';
import { get, includes, map, castArray, uniqueId } from 'lodash';

/**
* WordPress dependencies
Expand Down Expand Up @@ -79,8 +79,8 @@ export default {
optimist: { type: BEGIN, id: POST_UPDATE_TRANSACTION_ID },
} );
dispatch( removeNotice( SAVE_POST_NOTICE_ID ) );
const Model = wp.api.getPostTypeModel( getCurrentPostType( state ) );
new Model( toSend ).save().done( ( newPost ) => {
const basePath = wp.api.getPostTypeRoute( getCurrentPostType( state ) );
wp.apiRequest( { path: `/wp/v2/${ basePath }/${ post.id }`, method: 'PUT', data: toSend } ).done( ( newPost ) => {
dispatch( resetPost( newPost ) );
dispatch( {
type: 'REQUEST_POST_UPDATE_SUCCESS',
Expand Down Expand Up @@ -171,9 +171,9 @@ export default {
TRASH_POST( action, store ) {
const { dispatch, getState } = store;
const { postId } = action;
const Model = wp.api.getPostTypeModel( getCurrentPostType( getState() ) );
const basePath = wp.api.getPostTypeRoute( getCurrentPostType( getState() ) );
dispatch( removeNotice( TRASH_POST_NOTICE_ID ) );
new Model( { id: postId } ).destroy().then(
wp.apiRequest( { path: `/wp/v2/${ basePath }/${ postId }`, method: 'DELETE' } ).then(
() => {
dispatch( {
...action,
Expand Down Expand Up @@ -309,17 +309,17 @@ export default {
FETCH_REUSABLE_BLOCKS( action, store ) {
// TODO: these are potentially undefined, this fix is in place
// until there is a filter to not use reusable blocks if undefined
if ( ! has( wp, 'api.models.Blocks' ) && ! has( wp, 'api.collections.Blocks' ) ) {
const basePath = wp.api.getPostTypeRoute( 'wp_block' );
if ( ! basePath ) {
return;
}
const { id } = action;
const { dispatch } = store;

let result;
if ( id ) {
result = new wp.api.models.Blocks( { id } ).fetch();
result = wp.apiRequest( { path: `/wp/v2/${ basePath }/${ id }` } );
} else {
result = new wp.api.collections.Blocks().fetch();
result = wp.apiRequest( { path: `/wp/v2/${ basePath }` } );
}

result.then(
Expand Down Expand Up @@ -348,7 +348,8 @@ export default {
SAVE_REUSABLE_BLOCK( action, store ) {
// TODO: these are potentially undefined, this fix is in place
// until there is a filter to not use reusable blocks if undefined
if ( ! has( wp, 'api.models.Blocks' ) ) {
const basePath = wp.api.getPostTypeRoute( 'wp_block' );
if ( ! basePath ) {
return;
}

Expand All @@ -357,9 +358,12 @@ export default {

const { title, type, attributes, isTemporary } = getReusableBlock( getState(), id );
const content = serialize( createBlock( type, attributes ) );
const requestData = isTemporary ? { title, content } : { id, title, content };

new wp.api.models.Blocks( requestData ).save().then(
const data = isTemporary ? { title, content } : { id, title, content };
const path = isTemporary ? `/wp/v2/${ basePath }` : `/wp/v2/${ basePath }/${ id }`;
const method = isTemporary ? 'POST' : 'PUT';

wp.apiRequest( { path, data, method } ).then(
( updatedReusableBlock ) => {
dispatch( {
type: 'SAVE_REUSABLE_BLOCK_SUCCESS',
Expand All @@ -382,7 +386,8 @@ export default {
DELETE_REUSABLE_BLOCK( action, store ) {
// TODO: these are potentially undefined, this fix is in place
// until there is a filter to not use reusable blocks if undefined
if ( ! has( wp, 'api.models.Blocks' ) ) {
const basePath = wp.api.getPostTypeRoute( 'wp_block' );
if ( ! basePath ) {
return;
}

Expand All @@ -409,7 +414,7 @@ export default {
optimist: { type: BEGIN, id: transactionId },
} );

new wp.api.models.Blocks( { id } ).destroy().then(
wp.apiRequest( { path: `/wp/v2/${ basePath }/${ id }`, method: 'DELETE' } ).then(
() => {
dispatch( {
type: 'DELETE_REUSABLE_BLOCK_SUCCESS',
Expand Down
Loading