Create, Update, Delete, and Publish content with GraphQL Mutations

Jamie Barton
Jamie Barton

July 15, 2020

Create, Update, Delete, and Publish content with GraphQL Mutations

Since the very beginning, GraphCMS has boasted a GraphQL Mutations API alongside the traditional Query Content API, and it's free!

One of the biggest benefits of working on the Jamstack is that you get to pick the best of breed APIs. Whether you're building a static website, eCommerce store, Content Hub, or Mobile App, GraphCMS powered GraphQL Mutations will bring your project to life.

For each model you create in your project, GraphCMS automatically generates a mutation to create, update, delete, publish, and unpublish your content entries (records). These mutations are also backed up by a flexible, and secure permissions API.

Imagine we have a list of products, and we want to allow users to "upvote" products. The UI could look something like this:

Upvote products on click

You can also try this for yourself here.

To make this possible, you might reach for a serverless function, and you can easily build serverless functions with Next.js API routes. Here's a taste of what that looks like to create and publish votes for our products:

// https://github.com/GraphCMS/graphcms-examples/blob/master/using-mutations/src/pages/api/upvote.js
import { GraphQLClient } from 'graphql-request';
export default async ({ body }, res) => {
const graphcms = new GraphQLClient(
process.env.GRAPHCMS_ENDPOINT,
{
headers: {
authorization: `Bearer ${process.env.GRAPHCMS_MUTATION_TOKEN}`,
},
}
);
const { createVote } = await graphcms.request(
`mutation upvoteProduct($id: ID!) {
createVote(data: { product: { connect: { id: $id } } }) {
id
}
}`,
{ id: body.id }
);
res.status(201).json({ id: createVote.id });
};

On each request we send a GraphQL mutation to our GraphCMS endpoint with the id as a variable from the body of the request payload.

We are using connect to tell GraphCMS which product we want to reference when creating a new Vote. The createVote mutation is automatically generated for us when we create a model named Vote.

In the function above we are just creating an upvote, but what about if we want to publish this too? By default, GraphCMS only returns PUBLISHED content, so when we call createVote, we'll be creating a DRAFT record.

If we want to show the new vote count, we can also call the publishVote mutation after we create it!

await graphcms.request(
`mutation publishUpvote($id: ID!) {
publishVote(where: { id: $id }, to: PUBLISHED) {
id
}
}`,
{ id: createVote.id }
);

You can read more about all that is possible with the GraphCMS Mutation API over at the docs.

Have fun!


This site uses cookies to provide you with a better user experience. For more information, refer to our Privacy Policy