UNPKG

1.58 kBJavaScriptView Raw
1import { createServer } from 'http';
2import { execute, subscribe } from 'graphql';
3import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
4import { SubscriptionServer } from 'subscriptions-transport-ws';
5import bodyParser from 'body-parser';
6import express from 'express';
7import jwt from 'jsonwebtoken';
8import fs from 'fs';
9
10import schema from './schema';
11import loaders from './Loaders';
12
13const app = express();
14const PORT = 3000;
15const cert = process.env.NODE_ENV === 'dev'
16 ? 'hive'
17 : fs.readFileSync('/etc/letsencrypt/production/certs/madbean.ovh/fullchain.pem');
18
19app.use(bodyParser.json());
20
21const error = res => res.status(403).json({ error: 'No credentials sent!' });
22
23app.use((req, res, next) => {
24 const token = req.headers.authorization;
25 if (!token) return error(res);
26
27 jwt.verify(token, cert, { algorithms: ['RS256'] }, (err, { data }) => {
28 if (data && data.id && data.id !== '') {
29 next();
30 } else {
31 console.error(err);
32 error(res);
33 }
34 });
35});
36
37app.use('/graphql', graphqlExpress({
38 context: {
39 loaders,
40 },
41 schema,
42 tracing: true,
43 cacheControl: true,
44}));
45
46app.use('/graphiql', graphiqlExpress({
47 endpointURL: '/graphql',
48 subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`,
49}));
50
51const server = createServer(app);
52
53server.listen(PORT, () => {
54 new SubscriptionServer({
55 execute,
56 subscribe,
57 schema,
58 onConnect: () => console.log('new client connected'),
59 }, {
60 server,
61 path: '/subscriptions',
62 });
63});
64
65console.log(`Middle running at http://localhost:${PORT}`);