Getting started with GraphQL and Express
GraphQL is a query language that allows you to define the shape of your data and retrieve only the data you need from your server. It can be used with many different server-side frameworks, including Express, one of the most popular Node.js frameworks. In this tutorial, we'll walk through the steps to set up a GraphQL server with Express and retrieve data from a mock user database.
Step 1: Install dependencies
To get started, we'll need to install a few packages. First, we'll need to install Express:
```
npm install express
```
Next, we'll need to install `express-graphql`, which provides middleware to handle GraphQL requests in Express:
```
npm install express-graphql
```
Finally, we'll need to install `graphql`, which provides the core functionality for defining our schema and handling queries:
```
npm install graphql
```
Step 2: Define our schema
The schema defines the shape of our data and the queries that can be made to retrieve that data. In this example, we'll define a simple schema that allows us to retrieve information about users.
// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
type Query {
hello: String,
user(id: Int!): User
}
type User {
id: Int,
name: String,
age: Int,
gender: String,
address: String,
phone: String
}
`);
This defines a `Query` type with two fields: `user`, which takes an `id` argument and returns a single `User`, and `users`, which returns an array of all `User` objects. The `User` type defines the shape of the data we'll be returning, including fields for `id`, `name`, `age`, `gender`, `address`, and `phone`.
## Step 3: Create a mock data source
Next, we'll create a mock data source for our users.
// Sample users data
const users = [
{
id: 1,
name: 'John Doe',
age: 32,
gender: 'Male',
address: '123 Main St, Anytown USA',
phone: '555-555-1212'
},
{
id: 2,
name: 'Jane Smith',
age: 28,
gender: 'Female',
address: '456 Main St, Anytown USA',
phone: '555-555-1212'
}
];
This defines an array of three user objects, each with an `id`, `name`, `age`, `gender`, `address`, and `phone` field.
## Step 4: Implement our resolvers
The resolvers are functions that are responsible for retrieving the data for each field in our schema. In this example, we'll define two resolvers: one to retrieve a single user by `id`, and one to retrieve all users.
// Define the root resolver
const root = {
hello: () => 'Hello world!',
user: ({ id }) => users.find(user => user.id === id)
};
GraphQL and Express application in a single file
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
type Query {
hello: String,
user(id: Int!): User
}
type User {
id: Int,
name: String,
age: Int,
gender: String,
address: String,
phone: String
}
`);
// Sample users data
const users = [
{
id: 1,
name: 'John Doe',
age: 32,
gender: 'Male',
address: '123 Main St, Anytown USA',
phone: '555-555-1212'
},
{
id: 2,
name: 'Jane Smith',
age: 28,
gender: 'Female',
address: '456 Main St, Anytown USA',
phone: '555-555-1212'
}
];
// Define the root resolver
const root = {
hello: () => 'Hello world!',
user: ({ id }) => users.find(user => user.id === id)
};
// Create an express server and a GraphQL endpoint
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}));
app.listen(4000, () => {
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
});
This example sets up a basic GraphQL schema with a User type and a query to retrieve users by ID. The root resolver defines the behavior for the hello and user queries. Finally, an Express server is created and the GraphQL endpoint is mounted at /graphql.
With this code, you can start the server with node index.js and then query the API using a tool like GraphQL Playground or GraphiQL. For example, to retrieve user with ID 1, you can send the following query:
{
user(id: 1) {
id
name
age
gender
address
phone
}
}
This will return the following result:
"data": {
"user": {
"id": 1,
"name": "John Doe",
"age": 32,
"gender": "Male",
"address": "123 Main St, Anytown USA",
"phone": "555-555-1212"
}
}
}
No comments:
Post a Comment