GraphQL can be described as a query language for API. GraphQL was initiated by Facebook developers when they tried to build a better data fetching mechanism for their mobile application. By using GraphQL, frontend developers can request any data from the backend server with specified format and properties based on their actual needs.
Creating a server that has support for handling GraphQL-based requests has become easy nowadays. Express as a de-facto framework for building HTTP server has the capability to be integrated with Apollo Server which is a popular GraphQL server. Minimal modules that we need are express
, graphql
, and apollo-server-express
. For instance, we will set up a project and build the requirements. We utilize ESM syntax for building the sample program.
Firstly, we initiate the project and install the dependencies.
mkdir express-graphql
cd ./express-graphql
yarn init -y
yarn add express graphql apollo-server-express
Because we use ESM syntax, we need to set the type
property in the package.json
file.
{
"type": "module"
}
Then, we create a typeDefs.js
file to store the definition of the types for the GraphQL service.
import { gql } from 'apollo-server-express';
const typeDefs = gql`
type User {
id: ID!
name: String!
age: Int!
}
type Query {
getUsers: [User]
}
`;
export default typeDefs;
Next, we create a resolvers.js
file to store request resolvers for the service.
let users = [
{id: '1', name: 'Ali', age: 25},
{id: '2', name: 'Bill', gender: 45}
];
const resolvers = {
Query: {
getUsers: () => {
return users
},
}
}
export default resolvers;
Now, we can create the index.js
file as our main program.
import http from 'http';
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import typeDefs from './typeDefs.js';
import resolvers from './resolvers.js';
// setup GraphQL server
async function startApolloServer(app, typeDefs, resolvers) {
const apolloServer = new ApolloServer({typeDefs, resolvers});
await apolloServer.start();
apolloServer.applyMiddleware({app});
console.log('GraphQL Path:', apolloServer.graphqlPath);
}
// setup Express
const app = express();
app.use('/index', (req, res, next) => {
return res.json({'message': 'ok'});
});
// run GraphQL server
startApolloServer(app, typeDefs, resolvers);
// setup HTTP server
const server = http.createServer(app);
server.listen(3000);
Finally, we can run the server.
node ./index.js
Then, we test the functionality using Postman. The request uses the POST method and GraphQL body format to the endpoint assigned at http://localhost:3000/graphql
.
Comments
Post a Comment