-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
86 lines (79 loc) · 2.36 KB
/
main.ts
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
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { makeExecutableSchema } from '@graphql-tools/schema';
import cors, { CorsRequest } from 'cors';
import express from 'express';
import { readFileSync } from 'fs';
import { useServer } from 'graphql-ws/lib/use/ws';
import { createServer } from 'http';
import { join } from 'path';
import { WebSocketServer } from 'ws';
import { resolvers } from './resolvers';
import { cpuCronJob, memoryCronJob } from './services/top.service.js';
import { getEnv } from './utils/env.util.js';
import { isNotWhiteListed } from './utils/in-not-whitelisted.util.js';
const { port } = getEnv();
export interface Context {
ip: string;
}
(async () => {
const app = express();
const httpServer = createServer(app);
const typeDefs = readFileSync(join(__dirname, 'schema.graphql'), {
encoding: 'utf8',
});
const schema = makeExecutableSchema({ typeDefs, resolvers });
const wsServer = new WebSocketServer({
server: httpServer,
path: '/graphql',
});
const serverCleanup = useServer({ schema }, wsServer);
const apolloServer = new ApolloServer<Context>({
schema,
// Shutdown both the HTTP server and the WebSocketServer gracefully.
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
},
],
});
await apolloServer.start();
app.use(
'/graphql',
cors<CorsRequest>({
origin(origin, callback) {
if (origin && isNotWhiteListed(origin)) {
callback(new Error('CORS_NotWhitelisted'));
return;
}
callback(null, true);
},
}),
express.json(),
expressMiddleware(apolloServer, {
async context({ req }) {
return { ip: req.ip ?? req.header('x-forwarded-for') };
},
}),
);
httpServer.listen(port, 'localhost', () => {
console.log(
`🚀 WebSocket server URL: ws://localhost:${port}/graphql`,
);
console.log(
`🚀 Apollo serve URL: http://localhost:${port}/graphql`,
);
});
cpuCronJob.start();
memoryCronJob.start();
})()
.then()
.catch(console.error);