-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
43 lines (39 loc) · 1.49 KB
/
server.js
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
const {ApolloServer} = require('apollo-server');
const {ApolloGateway, RemoteGraphQLDataSource} = require('@apollo/gateway');
const jwt = require('jsonwebtoken');
const users = [
{id: 1, username: "imhassane", email: "imhassane@test.com", password: "imhassane"},
{id: 2, username: "imjannet", email: "imjannet@test.com", password: "imjannet"},
{id: 3, username: "christophe", email: "christophe@test.com", password: "christophe"},
{id: 4, username: "malik", email: "malik@test.com", password: "malik"},
];
const gateway = new ApolloGateway({
serviceList: [
{name: "users", url: "http://localhost:4001/graphql"},
{name: "posts", url: "http://localhost:4002/graphql"},
{name: "comments", url: "http://localhost:4003/graphql"}
],
buildService: ({url}) => new RemoteGraphQLDataSource({
url,
willSendRequest: ({request, context}) => {
if(context.user) request.http.headers.set("user", JSON.stringify(context.user));
}
})
});
const server = new ApolloServer({
gateway,
subscriptions: false,
context: async ({req}) => {
let token = req.headers.authorization || null;
if(token) {
try {
const {id} = await jwt.verify(token, "secret");
const user = users.find(u => u.id === id);
return { user };
} catch(ex) {
return {user: null};
}
}
}
});
module.exports = server;