-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
63 lines (56 loc) · 1.44 KB
/
index.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
import { ApolloServer, ServerInfo } from 'apollo-server';
import jwt from 'jsonwebtoken';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
type ConnectionParams = {
authToken: string;
}
const getCurrentUser = (token: string) => {
try {
if (token) {
return jwt.verify(token, 'very-secret-string');
}
return null;
} catch {
return null;
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req, connection }) => {
if (connection) {
return connection.context;
} else {
const tokenWithBearer = req.headers.authorization || '';
const token = tokenWithBearer.split(' ')[1];
const currentUser = getCurrentUser(token);
return {
currentUser
}
}
},
subscriptions: {
onConnect: (connectionParams, webSocket) => {
const { authToken } = (connectionParams as ConnectionParams);
if (authToken) {
const currentUser = getCurrentUser(authToken);
if (!currentUser) {
throw new Error('Missing auth token!');
}
return {
currentUser
};
}
throw new Error('Missing auth token!');
},
},
formatError: (error) => {
console.error(error);
return error;
}
});
server.listen().then(({ url, subscriptionsUrl }: ServerInfo) => {
console.log(`🚀 Server ready at ${url}`);
console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`);
})