-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphql.ts
More file actions
70 lines (61 loc) · 2.12 KB
/
graphql.ts
File metadata and controls
70 lines (61 loc) · 2.12 KB
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
import { makeExecutableSchema } from '@graphql-tools/schema';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { buildSubgraphSchema } from '@apollo/subgraph';
// import { applyMiddleware } from 'graphql-middleware';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import typeDefs from './graphql/types';
import resolvers from './graphql/resolver';
import http, { Server } from 'http';
import { Application, Request } from 'express';
import authenticate from './middleware/authenticate';
import { IContext } from './types/generic';
export default async function buildGraphQLServer(
app: Application,
): Promise<{ http: Server; gql: ApolloServer<IContext> }> {
const httpServer = http.createServer(app);
const schema = buildSubgraphSchema([
{
typeDefs,
resolvers,
},
]);
const wss = new WebSocketServer({
server: httpServer,
path: '/graphql', // for subscriptions
});
const serverCleanup = useServer(
{
schema,
context: async ({ req }: { req: Request }) => {
return await authenticate(req);
},
},
wss,
);
const context = async ({ req }: { req: Request }) => {
return await authenticate(req);
};
const server = new ApolloServer<IContext>({
schema,
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
},
],
csrfPrevention: true, // highly recommended
introspection: process.env.NODE_ENV === 'development',
});
await server.start();
app.use('/graphql', expressMiddleware(server, { context }));
return { http: httpServer, gql: server };
}