-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
53 lines (43 loc) · 1.61 KB
/
server.js
File metadata and controls
53 lines (43 loc) · 1.61 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
import { ApolloServer } from '@apollo/server';
import { expressMiddleware as apolloMiddleware } from '@apollo/server/express4';
import { makeExecutableSchema } from '@graphql-tools/schema';
import cors from 'cors';
import express from 'express';
import { readFile } from 'node:fs/promises';
import { useServer as useWsServer } from 'graphql-ws/use/ws';
import { createServer as createHttpServer } from 'node:http';
import { WebSocketServer } from 'ws';
import { authMiddleware, decodeToken, handleLogin } from './auth.js';
import { resolvers } from './resolvers.js';
const PORT = 9000;
const app = express();
app.use(cors(), express.json());
app.post('/login', handleLogin);
function getHttpContext({ req }) {
if (req.auth) {
return { user: req.auth.sub };
}
return {};
}
function getWsContext({ connectionParams }) {
const accessToken = connectionParams?.accessToken;
if (accessToken) {
const payload = decodeToken(accessToken);
return { user: payload.sub };
}
return {};
}
const typeDefs = await readFile('./schema.graphql', 'utf8');
const schema = makeExecutableSchema({ typeDefs, resolvers });
const apolloServer = new ApolloServer({ schema });
await apolloServer.start();
app.use('/graphql', authMiddleware, apolloMiddleware(apolloServer, {
context: getHttpContext,
}));
const httpServer = createHttpServer(app);
const wsServer = new WebSocketServer({ server: httpServer, path: '/graphql' });
useWsServer({ schema, context: getWsContext }, wsServer);
httpServer.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
// console.log(`GraphQL endpoint: http://localhost:${PORT}/graphql`);
});