Skip to content

Instantly share code, notes, and snippets.

@jasonbahl
Created May 2, 2018 21:03
Show Gist options
  • Save jasonbahl/c9455fe8cf8f060f7d115587560d1e4a to your computer and use it in GitHub Desktop.
Save jasonbahl/c9455fe8cf8f060f7d115587560d1e4a to your computer and use it in GitHub Desktop.
Gutenberg GraphQL Middleware
const { addFilter } = wp.hooks;
const { withState } = wp.components;
class GraphQLMiddleware {
constructor(config) {
this.query = config.attributes.graphql.query;
this.mutation = {};
this.config = _.extend( {}, config );
}
/**
* Check if it is a react component.
*
* @param {*} component Component or function.
*
* @return {boolean} Is react component or not.
*/
static isClassComponent( component ) {
return typeof component === 'function' && component.prototype && !! component.prototype.isReactComponent;
}
getSettings() {
this.blockConfigs = _.extend( {
title: '',
category: 'common',
attributes: {},
}, this.config );
const blockStates = _.extend( {
editable: '',
}, this.config.blockStates || {} );
delete this.blockConfigs.blockStates;
this.blockConfigs.edit = withState( blockStates )( ( props ) => {
const wrapperClassName = 'graphql-block ' + props.className;
props.graphql = this;
if ( this.config.edit ) {
if ( this.constructor.isClassComponent( this.config.edit ) ) {
return ( <div className={ wrapperClassName }><this.config.edit { ...props } /></div> );
}
return ( <div className={ wrapperClassName }>{ this.config.edit( props ) }</div> );
}
return ( <div className={ wrapperClassName }>{ this.edit( props ) }</div> );
} );
return this.blockConfigs;
}
save() {
return null;
}
}
const filterBlockSettings = (settings, name) => {
if ( settings && settings.attributes && settings.attributes.graphql ) {
const middleware = new GraphQLMiddleware(settings);
return middleware.getSettings();
}
return settings;
};
addFilter( 'blocks.registerBlockType', 'oshpd/registration/attributes', filterBlockSettings, 999 );
export default GraphQLMiddleware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment