Skip to content

Instantly share code, notes, and snippets.

@SachaG
Last active April 14, 2017 04:14
Show Gist options
  • Save SachaG/6f3d84f00716895b895bbb8e9f88fdb3 to your computer and use it in GitHub Desktop.
Save SachaG/6f3d84f00716895b895bbb8e9f88fdb3 to your computer and use it in GitHub Desktop.
// wrapper
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
export default function withMutation({name, args}) {
let mutation;
if (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
mutation = `
mutation ${name}(${args1}) {
${name}(${args2})
}
`
} else {
mutation = `
mutation ${name} {
${name}
}
`
}
return graphql(gql`${mutation}`, {
props: ({ownProps, mutate}) => ({
[name]: (vars) => {
return mutate({
variables: vars,
});
}
}),
});
}
// component
import { withMutation } from 'withMutation.js';
const MyComponent extends Component {
fetchMetaData() {
this.props.getMetaData({url: this.props.url}) /* get url from somewhere */
.then(result => {/* do something with the result */})
.catch(error => {/* do something with the error */})
},
render() {
return (/* render component here */)
}
}
const mutationOptions = {
name: 'getMetaData',
args: {url: 'String'},
}
export default withMutation(options)(MyComponent);
// schema
const schema = [`
type JSON
type Mutation {
getMetaData(url: String) : JSON
}
`];
// resolvers
import GraphQLJSON from 'graphql-type-json';
const rootResolvers = {
JSON: GraphQLJSON,
Mutation: {
getMetaData(root, { url }, context) {
const data = ... // make some kind of API call
return data;
},
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment