GraphQL mutations: Partial updates implementation

How to manage partial changes on existing resources with GraphQL mutations

PUT equivalent

type Author {
id: Int!
firstName: String
lastName: String
}
type Mutation {
updateAuthor(authorId: Int!, firstName: String, LastName: String): Author
}
updateAuthor: (_, { authorId, firstName, lastName }) => { 
const author = find(authors, { id: authorId });
if (!author) {
throw new Error(`Couldn’t find author with id ${authorId}`);
}
author.firstName = firstName;
author.lastName = lastName;
return author;
}
mutation {
updateAuthor ( authorId:1, firstName: "Aldous", lastName: "Huxley")
{
id
firstName
lastName
}
}
=>

{
"data": {
{
"id": 1,
"firstName": "Aldous",
"lastName": "Huxley"
}
}
mutation {
updateAuthor ( authorId:1, firstName: "Aldous")
{
id
firstName
lastName
}
}
=>

{
"data": {
{
"id": 1,
"firstName": "Aldous",
"lastName": null
}
}
mutation {
updateAuthor ( authorId:1, firstName: "Aldous", lastName: null)
{
id
firstName
lastName
}
}
=>

{
"data": {
{
"id": 1,
"firstName": "Aldous",
"lastName": null
}
}

Partial update management

updateAuthor: (_, {authorId, firstName, lastName}) => { 
const author = find(authors, { id: authorId });
if (!author) {
throw new Error(`Couldn't find author with id ${authorId}`);
}
if (firstName !== undefined) {
author.firstName = firstName;
}
if (lastName !== undefined) {
author.lastName = lastName;
}
return author;
}
if (firstName !== undefined) {
author.firstName = firstName;
}
updateAuthor: (root, args, context)
if (args.firstName !== undefined) {
author.firstName = args.firstName;
}
mutation {
updateAuthor ( authorId:1, firstName: "Aldous")
{
id
firstName
lastName
}
}
=> {
"data": {
{
"id": 1,
"firstName": "Aldous",
"lastName": "Davis"
}
}

Partial updates using query variables

mutation ($authorId: Int, $firstName: String, $lastName: String) {
updateAuthor($authorId, $firstName, $lastName)
{
id
firstName
lastName
}
}
{"authorId": 1, "firstName": "Aldous"}

Conclusion

Full Stack Architect, Creator of WorkflowGen, Advantys co-founder and CTO.