-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
82 lines (67 loc) · 2.3 KB
/
main.js
File metadata and controls
82 lines (67 loc) · 2.3 KB
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
// const perkJobs = require('./jobs/perk_jobs')
// const schedule = require('node-schedule')
import DBI from './db/db.js'
import express from 'express'
import bodyParser from 'body-parser'
import compression from 'compression'
import cors from 'cors'
import { statsModel } from './db/models/stats.js'
import mongoSanitize from 'express-mongo-sanitize'
// Use router provided by the routes in V1
import V1Router from './routes/API/V1.js'
/// ///////////////////////////
/// ///////////////////////////
// Stats //
import statsRouter from './routes/stats.js'
const app = express()
const port = process.env.PORT || 80
// Open connection if not already connected
DBI.initConnection()
app.use(bodyParser.urlencoded({ extended: true }))
// Allow Cross-origin
app.use(cors())
// Use Express compression
app.use(compression())
// Sanitize all user input for MongoDB
// Removes $ and . characters from user-supplied input in the following places:
// - req.body
// - req.params
// - req.headers
// - req.query
app.use(mongoSanitize())
// Middleware for setting header response to JSON
app.use((req, res, next) => {
res.setHeader('Content-Type', 'application/json') // Set header response to JSON, to prevent it from trying to render HTML in data
return next() // Goto next middleware / route
})
// Middleware for recording number of queries handled
// by application
//
// NO INFORMATION ABOUT USER IS STORED
app.use(async (req, res, next) => {
const path = req.path // Record path now in case next Middleware changs it somehow
next() // Go to next Middleware
// Record Global stats
statsModel.updateOne({ name: '*' }, {
$inc: { queries: 1 },
lastUpdated: new Date() // new Date() instead of Date.now() so it will work with toLocaleString()
}, { upsert: true }).exec()
if (path === '*') { return } // Don't record local stats for Global
// Record endpoint stats
statsModel.updateOne({ name: path }, {
$inc: { queries: 1 },
lastUpdated: new Date() // new Date() instead of Date.now() so it will work with toLocaleString()
}, { upsert: true }).exec()
})
/// ///////////////////////////
// V1 API //
app.use(
V1Router
)
app.use(
statsRouter() // Query Stats
)
// Open listening port for Express
app.listen(port, () => {
console.log(`Webserver started on port ${port}`)
})