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 fs from 'fs';
|
8 | import jwt from 'jsonwebtoken';
|
9 | import { makeExecutableSchema } from 'graphql-tools';
|
10 | import { glue } from 'schemaglue';
|
11 |
|
12 | import loaders from './Loaders';
|
13 | import { userMapper } from './Mapper/User';
|
14 |
|
15 | const app = express();
|
16 | const PORT = 3000;
|
17 | const isDev = process.env.NODE_ENV === 'dev';
|
18 | const cert = isDev
|
19 | ? 'hive'
|
20 | : fs.readFileSync('/etc/letsencrypt/production/certs/madbean.ovh/fullchain.pem');
|
21 |
|
22 | app.use(bodyParser.json());
|
23 |
|
24 | app.use((req, res, next) => {
|
25 | if (!req.headers.authorization) {
|
26 | next();
|
27 | } else {
|
28 | const bearer = req.headers.authorization;
|
29 | const token = bearer.replace('Bearer ', '');
|
30 |
|
31 | jwt.verify(token, cert, { algorithms: ['RS256'] }, (err, decoded) => {
|
32 | if (!decoded) {
|
33 | next();
|
34 | } else {
|
35 | const { data } = decoded;
|
36 | if (data) {
|
37 | req.user = userMapper(data);
|
38 | next();
|
39 | }
|
40 | }
|
41 | });
|
42 | }
|
43 | });
|
44 |
|
45 | const { schema, resolver } = glue('src/graphql');
|
46 | const executableSchema = makeExecutableSchema({
|
47 | typeDefs: schema,
|
48 | resolvers: resolver,
|
49 | });
|
50 |
|
51 | app.use('/graphql', graphqlExpress(req => ({
|
52 | context: {
|
53 | loaders,
|
54 | auth: {
|
55 | isAuthenticated: isDev ? true : !!req.user,
|
56 | scope: req.user && req.user.scope
|
57 | ? req.user.scope
|
58 | : null,
|
59 | },
|
60 | },
|
61 | schema: executableSchema,
|
62 | tracing: true,
|
63 | cacheControl: true,
|
64 | })));
|
65 |
|
66 | app.use('/graphiql', graphiqlExpress({
|
67 | endpointURL: '/graphql',
|
68 | subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`,
|
69 | }));
|
70 |
|
71 | const server = createServer(app);
|
72 |
|
73 | server.listen(PORT, () => {
|
74 | new SubscriptionServer({
|
75 | execute,
|
76 | subscribe,
|
77 | schema: executableSchema,
|
78 | onConnect: () => console.log('new client connected'),
|
79 | }, {
|
80 | server,
|
81 | path: '/subscriptions',
|
82 | });
|
83 | });
|
84 |
|
85 | console.log(`Middle running at http://localhost:${PORT}`);
|