-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
151 lines (138 loc) Β· 3.61 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const { ApolloServer, AuthenticationError } = require('apollo-server-express');
const fs = require('fs');
const https = require('https');
const http = require('http');
const jwt = require('jsonwebtoken');
const DataLoader = require('dataloader');
const config = require('./config/');
const schema = require('./app/graphql/schema/');
const resolvers = require('./app/graphql/resolvers/');
const loaders = require('./app/graphql/loaders/');
const {
sequelize,
models,
createUsersWithMessages,
} = require('./app/graphql/models/');
const isTest = !!process.env.TEST_DATABASE;
const getMe = async req => {
const token = req.headers['x-token'];
if (token) {
try {
return await jwt.verify(token, config.secret);
} catch (e) {
throw new AuthenticationError('Your session expired. Sign in again.');
}
}
};
class Server {
constructor() {
this.app = express();
this.apolloServer = new ApolloServer({
typeDefs: schema,
resolvers,
formatError: error => {
// remove the internal sequelize error message
// leave only the important validation error
const message = error.message
.replace('SequelizeValidationError: ', '')
.replace('Validation error: ', '');
return {
...error,
message,
};
},
context: async ({ req, connection }) => {
// Handles subscriptions
if (connection) {
return {
models,
loaders: {
user: new DataLoader(keys =>
loaders.user.batchUsers(keys, models)
),
},
};
}
if (req) {
const me = await getMe(req);
return {
models,
me,
secret: config.secret,
loaders: {
user: new DataLoader(keys =>
loaders.user.batchUsers(keys, models)
),
},
};
}
},
});
this.httpServer = this.configServer();
// init Subscriptions with GraphQL
this.apolloServer.installSubscriptionHandlers(this.httpServer);
this.router = express.Router();
this.initMiddlewares();
this.initRoutes();
this.start();
}
initMiddlewares() {
this.app.use(cors());
this.app.use(bodyParser.urlencoded({ extended: false }));
this.app.use(bodyParser.json());
this.apolloServer.applyMiddleware({ app: this.app, path: '/graphql' });
this.app.use(this.router);
}
configServer() {
// Create the HTTPS or HTTP server, per configuration
let server;
if (config.ssl) {
// Assumes certificates are in .ssl folder from package root. Make sure the files
// are secured.
server = https.createServer(
{
key: fs.readFileSync(`./ssl/${process.env.NODE_ENV}/server.key`),
cert: fs.readFileSync(`./ssl/${process.env.NODE_ENV}/server.crt`),
},
this.app
);
} else {
server = http.createServer(this.app);
}
return server;
}
initRoutes() {
this.router.get('/', (req, res) => {
res.send('π Hello GraphQL API!');
});
}
start() {
sequelize.sync({ force: isTest }).then(async () => {
if (isTest) {
createUsersWithMessages(new Date());
}
this.httpServer.listen({ port: config.port }, () => {
if (isTest) {
// 8881 due to port mapping in docker-compose
console.log(
'πππ [TEST] Server ready at',
`http${config.ssl ? 's' : ''}://${config.hostname}:8881${
this.apolloServer.graphqlPath
} <=== πππ`
);
} else {
console.log(
'πππ [DEV] Server ready at',
`http${config.ssl ? 's' : ''}://${config.hostname}:${config.port}${
this.apolloServer.graphqlPath
} <=== πππ`
);
}
});
});
}
}
new Server();