Skip to content

Instantly share code, notes, and snippets.

@ChrisMLee
Created December 17, 2017 16:25
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 ChrisMLee/56f3332d70635676a5455e7653d297de to your computer and use it in GitHub Desktop.
Save ChrisMLee/56f3332d70635676a5455e7653d297de to your computer and use it in GitHub Desktop.
Use Relay’s Input Object Mutations: Formatting Output Fields for Optimistic Updates
// connectionDefinitions returns a connectionType and its associated edgeType, given a node type.
const {
connectionType: VideoConnection,
edgeType: VideoEdge
} = connectionDefinitions({
nodeType: videoType,
connectionFields: () => ({
totalCount: {
type: GraphQLInt,
description: "A count of the total number of objects in this connection.",
resolve: conn => {
return conn.edges.length;
}
}
})
});
const videoMutation = mutationWithClientMutationId({
name: "AddVideo",
inputFields: {
title: {
type: GraphQLString,
description: "The title of the video."
},
duration: {
type: GraphQLInt,
description: "The duration of the video in seconds."
},
watched: {
type: GraphQLBoolean,
description: "Whether or not the viewer has watched the video."
}
},
outputFields: {
videoEdge: {
type: VideoEdge,
resolve: ({ video }, args) => {
return getVideos()
.then(existingVideos => {
return {
cursor: cursorForObjectInConnection(existingVideos, video),
node: video
};
})
.catch(error => error);
}
}
},
mutateAndGetPayload: args =>
new Promise((resolve, reject) => {
// this is will be fed in to the resolve function in outputFields
Promise.resolve(createVideo(args))
.then(video => {
resolve({ video });
})
.catch(reject);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment