-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
48 lines (43 loc) · 1.42 KB
/
app.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
44
45
46
47
48
const express = require('express');
const { ApolloServer, ApolloError } = require('apollo-server-express');
const { getStatusText, UNAUTHORIZED } = require('http-status-codes');
const helmet = require('helmet');
const morgan = require('morgan');
const token = require('./src/utils/token');
const logger = require('./src/utils/logger');
const typeDefs = require('./src/typeDefs');
const resolvers = require('./src/resolvers');
const models = require('./src/models');
const connectors = require('./src/connectors');
const { invalidToken } = require('./src/constants');
const app = express();
const getMe = async (req) => {
const authToken = req.headers['x-token'];
if (!authToken) return null;
const { ID, tokenID, tokenType } = token.verifyToken(authToken);
const exist = await models.User.checkToken(tokenID);
if (!exist) {
throw new ApolloError(invalidToken, getStatusText(UNAUTHORIZED));
}
return { ID, tokenID, tokenType };
};
const graphql = new ApolloServer({
typeDefs,
resolvers,
formatError: (error) => {
const message = error.message.replace('Context creation failed: ', '');
return {
...error,
message,
};
},
context: async ({ req }) => {
const me = await getMe(req);
return { models, me };
},
});
app.use(morgan('combined', { stream: logger.stream }));
app.use(helmet());
graphql.applyMiddleware({ app, path: '/hisab-kitab' });
connectors.Initialize();
module.exports = app;