GraphQL CRUD

GraphQL CRUD

GraphQL is a flexible query language and runtime for APIs, enabling clients to request exactly the data they need. This guide demonstrates how to implement Create, Read, Update, and Delete (CRUD) operations using GraphQL, focusing on the structure and examples of queries and mutations.

1. Setting Up a GraphQL Server

Install Required Packages

Using Node.js, install the necessary GraphQL packages:

bash

npm install graphql express express-graphql

Basic GraphQL Server Setup

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

// Define schema
const schema = buildSchema(`
  type User {
    id: ID!
    name: String!
    email: String!
  }

  input UserInput {
    name: String!
    email: String!
  }

  type Query {
    users: [User!]!
    user(id: ID!): User
  }

  type Mutation {
    createUser(input: UserInput): User
    updateUser(id: ID!, input: UserInput): User
    deleteUser(id: ID!): User
  }
`);

// Sample data
const users = [];

// Define resolvers
const root = {
  users: () => users,
  user: ({ id }) => users.find(user => user.id === id),
  createUser: ({ input }) => {
    const newUser = { id: String(users.length + 1), ...input };
    users.push(newUser);
    return newUser;
  },
  updateUser: ({ id, input }) => {
    const userIndex = users.findIndex(user => user.id === id);
    if (userIndex > -1) {
      users[userIndex] = { id, ...input };
      return users[userIndex];
    }
    throw new Error('User not found');
  },
  deleteUser: ({ id }) => {
    const userIndex = users.findIndex(user => user.id === id);
    if (userIndex > -1) {
      const deletedUser = users.splice(userIndex, 1)[0];
      return deletedUser;
    }
    throw new Error('User not found');
  },
};

// Start server
const app = express();
app.use(
  '/graphql',
  graphqlHTTP({
    schema,
    rootValue: root,
    graphiql: true,
  })
);

app.listen(4000, () => {
  console.log('GraphQL API running at http://localhost:4000/graphql');
});

2. CRUD Operations with GraphQL

Create (POST)

In GraphQL, creating data involves using a mutation to add new entries.

Example: Mutation

mutation {
  createUser(input: { name: "John Doe", email: "john.doe@example.com" }) {
    id
    name
    email
  }
}

Response

{
  "data": {
    "createUser": {
      "id": "1",
      "name": "John Doe",
      "email": "john.doe@example.com"
    }
  }
}

Read (GET)

The Read operation retrieves data using a query. Clients can specify the fields within the CRUD app they want.

Example: Query (All Users)

query {
  users {
    id
    name
    email
  }
}

Response

{
  "data": {
    "users": [
      { "id": "1", "name": "John Doe", "email": "john.doe@example.com" }
    ]
  }
}

Example: Query (Single User)

query {
  user(id: "1") {
    id
    name
    email
  }
}

Response

{
  "data": {
    "user": { "id": "1", "name": "John Doe", "email": "john.doe@example.com" }
  }
}

Update (PUT/PATCH)

Updating data in GraphQL involves using a mutation to modify existing entries.

Example: Mutation

mutation {
  updateUser(id: "1", input: { name: "John Updated", email: "john.updated@example.com" }) {
    id
    name
    email
  }
}

Response

{
  "data": {
    "updateUser": {
      "id": "1",
      "name": "John Updated",
      "email": "john.updated@example.com"
    }
  }
}

Delete (DELETE)

Deleting data involves using a mutation to remove an entry by ID.

Example: Mutation

mutation {
  deleteUser(id: "1") {
    id
    name
    email
  }
}

Response

{
  "data": {
    "deleteUser": {
      "id": "1",
      "name": "John Doe",
      "email": "john.doe@example.com"
    }
  }
}

Notable libraries and example projects

  1. NestJS Query - Library for building CRUD APIs with NestJS and GraphQL
  2. NestJS GraphQL Best Practice - Best practice example for building a CRUD API using NestJS and GraphQL