Introduction to express-graphql
Express-graphql is a fantastic tool to integrate GraphQL with your Express.js server, offering an easy way to create a flexible and efficient API. Here, we’ll explore various important APIs provided by express-graphql and provide code snippets to help you implement them.
Basic Setup
Let’s start with a basic setup for an express-graphql server:
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 } \`); // The root provides a resolver function for each API endpoint const root = { hello: () => { return 'Hello world!'; }, }; 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');
Implementing More Complex APIs
Now that you have a basic server running, let’s extend our GraphQL schema and resolver functions.
Adding Multiple Queries
const schema = buildSchema(\` type Query { hello: String goodbye: String } \`); const root = { hello: () => 'Hello world!', goodbye: () => 'Goodbye world!', };
Adding Mutations
Mutations allow you to create, update, or delete data. Here’s how to add them:
const schema = buildSchema(\` type Mutation { setMessage(message: String): String } type Query { getMessage: String } \`); let message = 'Hello world!'; const root = { setMessage: ({ message }) => { message = message; return message; }, getMessage: () => message, };
Working with Variables
Variables are a powerful feature of GraphQL:
// Define variables in the schema const schema = buildSchema(\` type Query { greet(name: String!): String } \`); // Resolvers use the variables passed in arguments const root = { greet: ({ name }) => \`Hello, \${name}!\`, };
Complete Application Example
Let’s put all of this together in a complete Express application:
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const schema = buildSchema(\` type Mutation { setMessage(message: String!): String } type Query { getMessage: String greet(name: String!): String } \`); let message = 'Hello world!'; const root = { setMessage: ({ message: newMessage }) => { message = newMessage; return message; }, getMessage: () => message, greet: ({ name }) => \`Hello, \${name}!\`, }; 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');
Conclusion
By leveraging express-graphql, you can build a more efficient and flexible API server. The provided code snippets here show basic to advanced use cases to get you started on your projects.
Hash: 91cabc13b9fbfda4f2b7396360831088832157ff057b2b30a58cc830b2495480