1 | import { createServer } from 'http';
|
2 | import { execute, subscribe } from 'graphql';
|
3 | import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
|
4 | import { SubscriptionServer } from 'subscriptions-transport-ws';
|
5 | import bodyParser from 'body-parser';
|
6 | import express from 'express';
|
7 | import jwt from 'jsonwebtoken';
|
8 | import fs from 'fs';
|
9 |
|
10 | import schema from './schema';
|
11 | import loaders from './Loaders';
|
12 |
|
13 | const app = express();
|
14 | const PORT = 3000;
|
15 | const cert = process.env.NODE_ENV === 'dev'
|
16 | ? 'hive'
|
17 | : fs.readFileSync('/etc/letsencrypt/production/certs/madbean.ovh/fullchain.pem');
|
18 |
|
19 | app.use(bodyParser.json());
|
20 |
|
21 | const error = res => res.status(403).json({ error: 'No credentials sent!' });
|
22 |
|
23 | app.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 |
|
37 | app.use('/graphql', graphqlExpress({
|
38 | context: {
|
39 | loaders,
|
40 | },
|
41 | schema,
|
42 | tracing: true,
|
43 | cacheControl: true,
|
44 | }));
|
45 |
|
46 | app.use('/graphiql', graphiqlExpress({
|
47 | endpointURL: '/graphql',
|
48 | subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`,
|
49 | }));
|
50 |
|
51 | const server = createServer(app);
|
52 |
|
53 | server.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 |
|
65 | console.log(`Middle running at http://localhost:${PORT}`);
|