-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (71 loc) · 2.42 KB
/
index.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
require('dotenv').config()
const cors = require('cors')
const express = require('express')
const PORT = process.env.PORT || 5000
const mongoose = require('mongoose')
const CronJob = require('cron').CronJob
const { getCountryNameBySnapshot, fetchData } = require('./helpers')
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true })
const countrySchema = mongoose.Schema({
name: { type: String, unique: true },
code: { type: String, unique: true },
snapshots: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Snapshot' }]
})
const snapshotSchema = mongoose.Schema({
timestamp: Date,
country: { type: mongoose.Schema.Types.ObjectId, ref: 'Country' },
cases: Number,
todayCases: Number,
deaths: Number,
todayDeaths: Number,
recovered: Number,
active: Number,
critical: Number
})
const Country = mongoose.model('Country', countrySchema)
const Snapshot = mongoose.model('Snapshot', snapshotSchema)
new CronJob('0 0 * * * *', fetchDataAndUpdateDb).start()
express()
.use(cors())
.get('/country/:code', async (req, res) => {
const before = req.query.before && new Date(req.query.before)
const after = req.query.after && new Date(req.query.after)
let timestampFilter = {timestamp: {}}
if (before) {
timestampFilter.timestamp.$lte = before
}
if (after) {
timestampFilter.timestamp.$gte = after
}
const code = req.params.code.toUpperCase()
const country = await Country.findOne({ code }, { _id: 0, __v: 0 }).populate(
'snapshots',
'deaths timestamp cases todayCases todayDeaths recovered active critical -_id',
(before || after) ? timestampFilter : {}
)
res.json(country)
})
.listen(PORT, () => console.log(`Listening on ${PORT}`))
async function fetchDataAndUpdateDb() {
const currentData = await fetchData()
const timestamp = new Date()
for (const snapshotItem of currentData) {
const countryName = getCountryNameBySnapshot(snapshotItem)
const snapshot = new Snapshot({
...snapshotItem,
timestamp
})
try {
const country = await Country.findOneAndUpdate({ name: countryName }, { $push: { snapshots: snapshot._id } }, { useFindAndModify: false })
if (!country) {
console.info('no country for', countryName)
continue
}
snapshot.country = country._id
await snapshot.save()
} catch (e) {
delete snapshot.country
console.error(e)
}
}
}