-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.ts
82 lines (69 loc) · 2.22 KB
/
server.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
import { ApolloServer } from "apollo-server-express";
import compression from "compression";
import express, { Application } from "express";
import { execute, GraphQLSchema, subscribe } from "graphql";
import { createServer, Server } from "http";
import { ApolloServerPluginDrainHttpServer } from "apollo-server-core";
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
class GraphQLServer {
// Propiedades
private app!: Application;
private httpServer!: Server;
private readonly DEFAULT_PORT = 3026;
private schema!: GraphQLSchema;
constructor(schema: GraphQLSchema) {
if (schema === undefined) {
throw new Error("Necesitamos un schema de GraphQL para trabajar con APIs GraphQL");
}
this.schema = schema;
this.init();
}
private init() {
this.configExpress();
this.configApolloServerExpress();
// this.configRoutes();
}
private configExpress() {
this.app = express();
this.app.use(compression());
this.httpServer = createServer(this.app);
}
private async configApolloServerExpress() {
// Create our WebSocket server using the HTTP server we just set up.
const wsServer = new WebSocketServer({
server: this.httpServer,
path: '/graphql',
});
// Save the returned server's info so we can shutdown this server later
const serverCleanup = useServer({ schema: this.schema }, wsServer);
// Set up ApolloServer.
const server = new ApolloServer({
schema: this.schema,
csrfPrevention: true,
cache: "bounded",
plugins: [
// Proper shutdown for the HTTP server.
ApolloServerPluginDrainHttpServer({ httpServer: this.httpServer }),
// Proper shutdown for the WebSocket server.
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
},
],
});
await server.start();
server.applyMiddleware({ app: this.app, cors: true });
}
listen(callback: (port: number) => void): void {
this.httpServer.listen(+this.DEFAULT_PORT, () => {
callback(+this.DEFAULT_PORT);
});
}
}
export default GraphQLServer;