Step-by-Step Example
1. Set Up the Project
Create a new project directory, initialize it, and install the necessary dependencies:
mkdir graphql-mutations
cd graphql-mutations
npm init -y
Output:
2. Install dependencies
Install Express and its associated extension Express-GraphQL in addition to the GraphQL package itself:
npm install express express-graphql graphql
3. Create the index.js File
In your project directory, create an index.js file and set up a basic Express server with GraphQL.
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// Mock data
let books = [
{ id: 1, title: '1984', author: 'George Orwell' },
{ id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' }
];
// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
type Book {
id: Int
title: String
author: String
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String!, author: String!): Book
updateBook(id: Int!, title: String, author: String): Book
deleteBook(id: Int!): Book
}
`);
// The root provides a resolver function for each API endpoint
const root = {
books: () => books,
addBook: ({ title, author }) => {
const book = { id: books.length + 1, title, author };
books.push(book);
return book;
},
updateBook: ({ id, title, author }) => {
const book = books.find(book => book.id === id);
if (!book) throw new Error('Book not found');
if (title) book.title = title;
if (author) book.author = author;
return book;
},
deleteBook: ({ id }) => {
const index = books.findIndex(book => book.id === id);
if (index === -1) throw new Error('Book not found');
const deletedBook = books.splice(index, 1)[0];
return deletedBook;
}
};
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));
4. Run the server:
Start our server by running:
node index.js
5. Access GraphiQL:
Open our browser and navigate to http://localhost:4000/graphql. we should see the GraphiQL interface, which is an in-browser tool for writing, validating, and testing GraphQL queries.
Mutations in GraphQL
GraphQL is a query language for REST APIs created by Facebook which is designed to provide more efficiency, flexibility, and superiority in data handling.
While GraphQL queries are used to retrieve information, mutations are used to perform data operations on the server, similar to HTTP Commands like POST, PUT, PATCH, and DELETE in REST APIs. In this article, We will learn about the Mutations in GraphQL in detail.