UNPKG

2.11 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 fs from 'fs';
8import jwt from 'jsonwebtoken';
9import { makeExecutableSchema } from 'graphql-tools';
10import { glue } from 'schemaglue';
11
12import loaders from './Loaders';
13import { userMapper } from './Mapper/User';
14
15const app = express();
16const PORT = 3000;
17const isDev = process.env.NODE_ENV === 'dev';
18const cert = isDev
19 ? 'hive'
20 : fs.readFileSync('/etc/letsencrypt/production/certs/madbean.ovh/fullchain.pem');
21
22app.use(bodyParser.json());
23
24app.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
45const { schema, resolver } = glue('src/graphql');
46const executableSchema = makeExecutableSchema({
47 typeDefs: schema,
48 resolvers: resolver,
49});
50
51app.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
66app.use('/graphiql', graphiqlExpress({
67 endpointURL: '/graphql',
68 subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`,
69}));
70
71const server = createServer(app);
72
73server.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
85console.log(`Middle running at http://localhost:${PORT}`);