Imagine a task management application where users can perform the following operations:
* Create a new task * Mark a task as completed * Retrieve a list of tasks
Assuming you have Node.js and npm installed, let's create a new project and install necessary packages.
Create a new project folder
mkdir graphql-task-manager cd graphql-task-manager
Initialize the project and answer the prompts
npm init -y
Install required packages
npm install express express-graphql graphql
Create a `task.js` file to represent a simple task model.
class Task { constructor(id, title, completed) { this.id = id; this.title = title; this.completed = completed; } } module.exports = Task;
In this step, we'll define the GraphQL schema for our task management system. The schema describes the types of data that can be queried and mutated and how they are related.
1. Import Necessary Modules:
We begin by importing the required modules from the `graphql` package and our `task` model.
const { GraphQLObjectType, GraphQLString, GraphQLBoolean, GraphQLList, GraphQLSchema } = require('graphql'); const Task = require('./task');
2. Create a Task Model:
Define a simple `Task` model to represent a task with an `id`, `title`, and `completed` status. This model will be used in the schema.
class Task { constructor(id, title, completed) { this.id = id; this.title = title; this.completed = completed; } } module.exports = Task; ```
3. Define TaskType:
Create a `TaskType` GraphQLObjectType to represent the structure of a task. It includes fields such as `id`, `title`, and `completed`.
const TaskType = new GraphQLObjectType({ name: 'Task', fields: () => ({ id: { type: GraphQLString }, title: { type: GraphQLString }, completed: { type: GraphQLBoolean }, }), });
4. Root Query:
Define a `RootQuery` GraphQLObjectType to handle queries. In this example, we provide a single query field called `tasks` that returns a list of tasks.
const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { tasks: { type: new GraphQLList(TaskType), resolve(parent, args) { return tasks; // Assuming 'tasks' is an array of Task objects }, }, }, });
5. Mutation:
Introduce a `Mutation` GraphQLObjectType to handle mutations. We'll start with a mutation called `addTask`, which allows users to create a new task.
const Mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addTask: { type: TaskType, args: { title: { type: GraphQLString }, completed: { type: GraphQLBoolean }, }, resolve(parent, args) { const newTask = new Task(String(tasks.length + 1), args.title, args.completed || false); tasks.push(newTask); return newTask; }, }, }, });
6. Create GraphQLSchema:
Combine the `RootQuery` and `Mutation` into a single GraphQL schema using the `GraphQLSchema` class.
module.exports = new GraphQLSchema({ query: RootQuery, mutation: Mutation, });
This step sets up the foundation for handling queries and mutations related to tasks in our GraphQL schema. It defines the types, queries, and mutations that our GraphQL API will support.
Set up an Express server to handle GraphQL requests.
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const schema = require('./schema');
const app = express();
app.use('/graphql', graphqlHTTP({ schema, graphiql: true, // Enable GraphiQL interface for testing }));
const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}/graphql`); });
Run the server and test the GraphQL API.
node server.js
Visit `http://localhost:3000/graphql` in your browser to open the GraphiQL interface. You can use it to run queries and mutations against your GraphQL API.
Try running some queries and mutations in the GraphiQL interface.
query { tasks { id title completed } }
mutation { addTask(title: "Learn GraphQL Mutations") { id title completed } }