-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
253 lines (218 loc) · 6.24 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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
const serverless = require("serverless-http");
const express = require("express"),
createNamespace = require("continuation-local-storage").createNamespace,
morgan = require("morgan"),
bodyParser = require("body-parser"),
helmet = require("helmet"),
winston = require("winston"),
cors = require("cors");
customUrlParser = require("url");
const rootPrefix = ".";
const basicHelper = require(rootPrefix + "/helpers/basic"),
coreConstants = require(rootPrefix + "/helpers/coreConstants"),
customMiddleware = require(rootPrefix + "/helpers/customMiddleware"),
sanitizer = require(rootPrefix + "/helpers/sanitizer");
const requestSharedNameSpace = createNamespace("turfBookingApiNamespace");
const apiRoutes = require(rootPrefix + "/routes/index");
const mongoConnection = require("./db/mongoConnection");
mongoConnection;
const logger = winston.createLogger({
level: "info",
format: winston.format.json(),
transports: [new winston.transports.Console()],
});
morgan.token("id", function getId(req) {
return req.id;
});
// eslint-disable-next-line no-unused-vars
morgan.token("pid", function getPid(req) {
return process.pid;
});
// eslint-disable-next-line no-unused-vars
morgan.token("endTime", function getEndTime(req) {
return Date.now();
});
// eslint-disable-next-line no-unused-vars
morgan.token("endDateTime", function getEndDateTime(req) {
return basicHelper.logDateFormat();
});
morgan.token("ipAddress", function getIpAddress(req) {
return req.headers["x-real-ip"];
});
/**
* First log line of request start
*
* @param {object} req
* @param {object} res
* @param {object} next
*
* @returns {Promise<void>}
*/
const startRequestLogLine = function (req, res, next) {
const message = [
"Started '",
customUrlParser.parse(req.originalUrl).pathname, // Todo: deprecation fix
"' '",
req.method,
"' at ",
basicHelper.logDateFormat(),
];
console.info(message.join(""));
if (!basicHelper.isProduction()) {
logger.info(
"\nHEADERS FOR CURRENT REQUEST=====================================\n",
JSON.stringify(req.headers),
"\n========================================================"
);
}
next();
};
/**
* Get request params
*
* @param {object} req
* @return {*}
*/
const getRequestParams = function (req) {
// IMPORTANT NOTE: Don't assign parameters before sanitization.
if (req.method === "POST") {
return req.body;
} else if (req.method === "GET") {
return req.query;
}
return {};
};
/**
* Assign params
*
* @param {object} req
* @param {object} res
* @param {object} next
*
* @returns {Promise<void>}
*/
const assignParams = function (req, res, next) {
req.decodedParams = getRequestParams(req);
/**
* Internal decoded params are for parameters which are not passed in the request from outside.
*/
req.internalDecodedParams = {};
next();
};
/**
* Set request debugging/logging details to shared namespace.
* @param {object} req
* @param {object} res
* @param {object} next
*
* @returns {Promise<void>}
*/
const appendRequestDebugInfo = function (req, res, next) {
requestSharedNameSpace.run(function () {
requestSharedNameSpace.set("reqId", req.id);
requestSharedNameSpace.set("startTime", req.startTime);
next();
});
};
/**
* Set response headers
*
* @param {object} req
* @param {object} res
* @param {object} next
*
* @returns {Promise<void>}
*/
const setResponseHeader = async function (req, res, next) {
res.setHeader("Pragma", "no-cache");
res.setHeader(
"Cache-Control",
"no-store, no-cache, max-age=0, must-revalidate, post-check=0, pre-check=0"
);
res.setHeader("Vary", "*");
res.setHeader("Expires", "-1");
res.setHeader("Last-Modified", new Date().toUTCString());
next();
};
// Set worker process title.
process.title = "API node worker";
// Create express application instance.
const app = express();
// Add id and startTime to request.
app.use(customMiddleware());
app.use(
cors({
origin: [
"http://localhost:3000",
/turf-reservation-.*\.vercel\.app$/,
"https://turf-reservation-web.vercel.app/",
],
credentials: true,
})
);
// Load Morgan
app.use(
morgan(
"[:pid][:id][:endTime][" +
coreConstants.APP_NAME +
'] Completed with ":status" in :response-time ms at :endDateTime - ":res[content-length] bytes" - ":ipAddress" ":remote-user" - "HTTP/:http-version :method :url" - ":referrer" - ":user-agent" \n\n'
)
);
app.use(function (req, res, next) {
let data = "";
req.on("data", function (chunk) {
data += chunk;
});
req.on("end", function () {
req.rawBody = data;
});
next();
});
// Helmet helps secure Express apps by setting various HTTP headers.
app.use(helmet());
// Node.js body parsing middleware. Default limit is 100kb
app.use(bodyParser.json({ limit: "2mb" }));
// Parsing the URL-encoded data with the qs library (extended: true). Default limit is 100kb
app.use(bodyParser.urlencoded({ extended: true, limit: "2mb" }));
// Start Request logging. Placed below static and health check to reduce logs.
app.use(appendRequestDebugInfo, startRequestLogLine);
// Set response headers.
app.use(setResponseHeader);
/**
* NOTE: For API routes: first sanitize and then assign params.
*/
app.use(
"/api",
sanitizer.sanitizeBodyAndQuery,
assignParams,
function (request, response, next) {
apiRoutes(request, response, next);
}
);
// middleware to handle 404 errors, dont use response helper.
app.use(function (req, res, next) {
res.status(404).send({ error: "Route Not Found" });
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: "Something went wrong!" });
});
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
// If running in development mode, start the server on port 8080, else export handler for lambda
if (coreConstants.environment === "development") {
require("dotenv").config();
console.log("Server running on 8080");
app.listen(8080);
module.exports = { handler: app };
} else {
// Export the handler for Lambda on production
console.log("Exporting handler for lambda");
module.exports.handler = serverless(app);
}