Skip to content

Instantly share code, notes, and snippets.

@scf4
Last active February 5, 2018 23:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scf4/5ba0ab1292fdd09c4f84fa69c1a1dc93 to your computer and use it in GitHub Desktop.
Save scf4/5ba0ab1292fdd09c4f84fa69c1a1dc93 to your computer and use it in GitHub Desktop.
graphql koa app.js with http and ws endpoints
/* eslint-disable no-console */
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import cors from 'kcors';
import { SubscriptionServer as WebSocketServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { graphqlKoa, graphiqlKoa as graphiqal } from 'graphql-server-koa';
import { formatError, isInstance } from 'apollo-errors';
import setupContext from 'modules/context';
import config from 'config';
import routes from 'routes';
import schema from 'executableSchema';
const app = new Koa();
app.use(bodyParser());
app.use(cors());
/* Catch errors */
app.use(async (ctx, next) => {
try {
await next();
} catch (error) {
ctx.status = error.statusCode || error.status || 500;
ctx.body = {
error: (isInstance(error) || config.env !== 'production')
? error.message
: null,
};
}
});
/* Setup GraphQL Endpoints */
/* HTTP */
routes.post(config.server.httpPath, (ctx) => graphqlKoa({
schema,
formatError: (error) => formatError(error, config.env === 'production'), // True = doesn't return internal errors
rootValue: {},
context: setupContext({
token: ctx.headers.authorization,
ip: ctx.request.ip,
}),
})(ctx));
// Graphiqal
routes.get('/o', graphiqal({
endpointURL: config.server.httpPath,
}));
app.use(routes.routes());
console.log(`Running in ${process.env.NODE_ENV} mode\n`);
console.log('Starting HTTP server...');
app.listen(config.server.httpPort);
console.log('Starting WS server...');
WebSocketServer.create({
schema,
execute,
subscribe,
onConnect: async ({ authToken }, socket) => {
console.log(`${socket._socket.remoteAddress} connected`);
return setupContext({ token: authToken, ip: socket._socket.remoteAddress });
},
}, {
server: app,
path: config.server.wsPath,
});
const rootUrl = `localhost:${config.server.httpPort}`;
console.log(`HTTP Endpoint: http://${rootUrl}${config.server.httpPath}`);
console.log(`WS Endpoint: ws://${rootUrl}${config.server.wsPath}`);
console.log(`GraphiQL: http://${rootUrl}/o`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment