Skip to main content

Setup an HTTP server

Here's an example using express-graphql:

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const typeDefs = require('./graphql/types');
const resolvers = require('./graphql/resolvers');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true,
}));
app.listen(3000, () => {
console.info('Listening on http://localhost:3000/graphql');
});

And you can test your queries using built-in GraphiQL;

Adding Subscriptions support#

graphql-ws offers a server and client implementation for transporting subscription events over WebSockets.

const http = require('http');
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { execute, subscribe } = require('graphql');
const ws = require('ws'); // yarn add ws
const { useServer } = require('graphql-ws/lib/use/ws');
const typeDefs = require('./graphql/types');
const resolvers = require('./graphql/resolvers');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
const app = express();
app.use(
'/graphql',
graphqlHTTP({
schema,
graphiql: true,
})
);
const server = http.createServer(app);
const wsServer = new ws.Server({
server,
path: '/graphql',
});
server.listen(3000, () => {
useServer(
{
schema,
execute,
subscribe,
},
wsServer,
);
console.info('Listening on http://localhost:3000/graphql');
});