Skip to content

Instantly share code, notes, and snippets.

@SachaG
Last active March 4, 2018 17:43
Show Gist options
  • Save SachaG/574fd1a6cd9420381eec15b8d15795d5 to your computer and use it in GitHub Desktop.
Save SachaG/574fd1a6cd9420381eec15b8d15795d5 to your computer and use it in GitHub Desktop.
Quick Apollo Mutations

In my app, I have a lot of super-simple mutations that take in arguments, query the server, and return a JSON object (or sometimes, nothing at all). Always having to define types and write mutation boilerplate was a pain, so I created a simple withMutation higher-order component.

Don't forget to call your mutation with variables:

this.props.withMutation({variables: {foo: '123', bar: 'abc'}}).then(/*...*/).catch(/*...*/);

Note: make sure you use graphql-tools v0.8.3 or above for the custom scalar type to work properly.

// define component1, component2, etc. here
// will pass mutation as this.props.myMutation
export default withMutation({
name: 'myMutation',
args: {foo: 'String', bar: 'String'},
})(component1);
// will pass mutation as this.props.myOtherMutation
// this time, we don't have any arguments
export default withMutation({
name: 'myOtherMutation'
})(component2);
// etc.
// server-side boilerplate. Nothing special here, except that the mutation's return type has to be JSON
import { makeExecutableSchema } from 'graphql-tools';
const GraphQLJSON = require('graphql-type-json');
const schemaString = `
scalar JSON
type Mutation {
myMutation (
foo: String,
bar: String,
): JSON
}
`;
const resolveFunctions = {
JSON: GraphQLJSON,
Mutation: {
myMutation(root, {foo, bar}, context) {
// make some kind of API call, server operation, etc.
return {
// return any JSON object
}
}
}
};
const jsSchema = makeExecutableSchema({ typeDefs: schemaString, resolvers: resolveFunctions });
// the withMutation higher-order component.
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
export default function withMutation({name, args}) {
const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String
const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url
return graphql(gql`
mutation ${name}(${args1}) {
${name}(${args2})
}
`, {
name: name
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment