-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
executable file
·87 lines (76 loc) · 2.65 KB
/
server.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('dotenv').config();
}
import { ApolloServer } from '@apollo/server';
import { config } from './config';
import { expressMiddleware } from '@apollo/server/express4';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const serverlessExpress = require('@vendia/serverless-express');
import * as express from 'express';
import * as core from 'express-serve-static-core';
import { json } from 'body-parser';
import * as cors from 'cors';
import { typeDefs, resolvers } from './routes/graphql';
import { jwtController } from './controllers';
import * as Sentry from '@sentry/serverless';
import helmet from 'helmet';
import { RateLimiterMiddleware } from './middlewares';
import { sync } from './models';
import { CreateRoutes } from './controllers/CreateRoutes';
const getIpAddress = (request: express.Request): string | undefined => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
return request.clientIp || undefined;
};
const getDeviceUniqueIdentifier = (request: express.Request): string | undefined => {
if (request?.headers?.deviceUniqueIdentifier) {
return request.headers.deviceUniqueIdentifier.toString();
}
return;
};
export const createApp = async (): Promise<core.Express> => {
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: config.nodeEnv !== 'production',
});
server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
const app = express();
await sync();
return new Promise((resolve, reject) => {
const ready = err => {
if (err) {
reject(err);
}
CreateRoutes(app);
app.use(
cors(),
json(),
helmet(),
expressMiddleware(server, {
context: async ({ req, res }) => {
const { event, context } = serverlessExpress.getCurrentInvoke();
return {
expressRequest: req,
expressResponse: res,
lambdaEvent: event,
lambdaContext: context,
...(await jwtController.createAuthScope(req.headers.authorization)),
ip: getIpAddress(req),
deviceUniqueIdentifier: getDeviceUniqueIdentifier(req),
userAgent: req.headers['user-agent'],
};
},
}),
);
resolve(app);
};
app.use(new RateLimiterMiddleware(ready).middleware);
});
};
async function setup(event, context) {
const app = await createApp();
return serverlessExpress({ app })(event, context);
}
exports.handler = Sentry.AWSLambda.wrapHandler(setup);