Skip to content

Instantly share code, notes, and snippets.

@kadamwhite
Last active March 18, 2019 19:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kadamwhite/85efe893ef106382a61700c7e3425d53 to your computer and use it in GitHub Desktop.
Save kadamwhite/85efe893ef106382a61700c7e3425d53 to your computer and use it in GitHub Desktop.
wpapi lightweight testbed
/* eslint-disable no-console */
/**
* A little module that adds a wpapi() method to the window object.
*
* wpapi() takes an API path (e.g. /wp/v2/posts), optionally containing string query parameters,
* or a query-less API path and a hash object of query param objects.
*/
( context => {
const { root, nonce } = context.WP_API_Settings;
const trailingSlashIt = str => str.replace( /\/*$/, '/' );
if ( trailingSlashIt( 'someStr' ) !== 'someStr/' ) throw new Error( 'trailingSlashIt failed' );
const noLeadingSlash = str => str.replace( /^\/*/, '' );
if ( noLeadingSlash( '/someStr' ) !== 'someStr' ) throw new Error( 'noLeadingSlash failed' );
const apiUrl = path => `${ trailingSlashIt( root ) }${ noLeadingSlash( path ) }`;
if ( apiUrl( '/wp/v2/posts' ) !== `${ root }wp/v2/posts` ) throw new Error( `apiUrl failed: ${ apiUrl( 'wp/v2/posts' ) }` );
// const parseQuery = url => {
// const queryParams = url.replace( /.*\?/, '' );
// if ( ! queryParams ) {
// return {};
// }
// return queryParams.split( '&' ).reduce( ( params, keyValPair ) => {
// const [ key, value ] = keyValPair.split( '&' );
// if ( ! key || value === undefined ) {
// throw new Error( `Invalid key-value pair: ${ keyValPair }` );
// }
// return {
// ...params,
// [ key ]: value,
// };
// }, {} );
// };
// if ( parseQuery( 'http://apiroot.local?rest_route=/wp/v2/posts' ) )
const addParams = ( url, params ) => {
if ( typeof params !== 'object' || ! Object.keys( params ).length ) {
return url;
}
// Does not handle array arguments.
const queryParams = Object.keys( params ).reduce(
( keyValPairs, key ) => keyValPairs.concat( `${ key }=${ params[ key ] }` ),
[]
).join( '&' );
if ( url.indexOf( 'rest_route=' > -1 ) ) {
return `${ url }&${ queryParams }`;
} else {
return `${ url.replace( /\?.*$/, '' ) }?${ queryParams }`;
}
};
const headersToObj = headers => [ ...headers ].reduce( ( memo, [ name, value ] ) => ( {
...memo,
[ name ]: value,
} ), {} );
const wpapi = ( path, urlParams = {}, options = {} ) => {
const url = addParams( apiUrl( path ), urlParams );
const fetchOptions = {
headers: {
Accept: 'application/json, */*;q=0.1',
'Content-Type': 'application/json',
'X-WP-Nonce': nonce,
},
credentials: 'include',
...options,
};
return fetch( url, fetchOptions ).then( resp => {
if ( resp.status >= 200 && resp.status < 300 ) {
if ( resp.json ) {
return resp.json().then( data => {
Object.defineProperty( data, '_headers', {
value: headersToObj( resp.headers ),
writable: false,
} );
return data;
});
}
}
throw ( resp );
} );
};
context.wpapi = wpapi;
console.log( 'wpapi() method now available in the console!' );
} )( window );
<?php
/*
Plugin Name: WP REST API JS testbed environment.
Description: Add browser globals which can be used to query the API as an auth'd user.
Version: 1.0
Author: K. Adam White
Author URI: https://wordpress.org/support/profile/kadamwhite
*/
function api_testbed_enqueue_script() {
wp_enqueue_script(
'api-testbed',
plugin_dir_url( __FILE__ ) . 'api-testbed.js',
[],
filemtime( trailingslashit( dirname( __FILE__ ) ) . 'api-testbed.js' ),
true
);
wp_localize_script( 'api-testbed', 'WP_API_Settings', [
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' ),
] );
}
add_action( 'wp_enqueue_scripts', 'api_testbed_enqueue_script' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment