-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.js
87 lines (65 loc) · 1.93 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
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
require("dotenv").config()
const express = require('express')
const rateLimit = require("express-rate-limit");
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')
const db = require('./utils/db')
const projectTwoRoutes = require('./routes/projectTwo')
const projectOneRoutes = require('./routes/projectOne')
const getChainData = require("./utils/getChainData")
const removeTrailingSlash = require('./middleware/removeTrailingSlash');
const PORT = process.env.PORT || 3001
// Call getChainData here to begin chain data update loop and start caching new data to database
getChainData()
const app = express()
// Limit request rate
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
// apply to all requests
app.use(cors())
app.use(bodyParser.text())
// limit requests
app.use(limiter);
// remove trailing slash
app.use(removeTrailingSlash);
// Logging
app.use(morgan('tiny'))
// Remove trailing slash
// Routes
app.use(/^\/$/, (req, res) => {
res.send("Welcome to the Fomocraft API!")
})
// add cached data to req
app.use('/v1/projectTwo', async (req, res, next) => {
const client = db.getClient()
try {
await db.getCachedprojectTwoData(client).then(result => req.chainData = result)
}
catch(err){
console.log("error getting data")
console.log(err)
}
next()
})
// add cached data to req
app.use('/v1/projectOne', async (req, res, next) => {
const client = db.getClient()
try {
await db.getCachedprojectOneData(client).then(result => req.chainData = result)
}
catch(err){
console.log("error getting data")
console.log(err)
}
next()
})
app.use('/v1/projectOne', projectOneRoutes)
app.use('/v1/projectTwo', projectTwoRoutes)
app.use((req, res) => {
res.status(404).json({error: true, message: "Resource not found"})
})
app.listen(PORT)
console.log(`App listening on ${PORT}`)