Implementing GraphQL in a Web Application: A Practical Example

Use Case

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

Step 1: Set Up the Project

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

Step 2: Create a Simple Task Model

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;

Step 3: Set Up GraphQL Schema

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.

Step 4: Create Express Server

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`);
});

Step 5: Run the Server

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.

Step 6: Test GraphQL Queries and Mutations

Try running some queries and mutations in the GraphiQL interface.

Query

query {
  tasks {
    id
    title
    completed
  }
}

Mutation

mutation {
  addTask(title: "Learn GraphQL Mutations") {
    id
    title
    completed
  }
}
teaching_assistant/workflow/simple_task_management.txt · Last modified: 2024/01/16 11:21 by Ralph
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0