Created
December 17, 2017 16:25
-
-
Save ChrisMLee/56f3332d70635676a5455e7653d297de to your computer and use it in GitHub Desktop.
Use Relay’s Input Object Mutations: Formatting Output Fields for Optimistic Updates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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