-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
228 lines (219 loc) · 6.45 KB
/
index.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
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
import express from 'express';
import cors from 'cors';
import moment from 'moment';
import { isDate } from './utils/Validation';
import refreshData from './utils/refreshData';
import mysql from 'mysql2';
import * as dotenv from 'dotenv';
import NodeCache from 'node-cache';
import StateCodeMap from './stateCodeMap';
import swaggerUi from 'swagger-ui-express';
import swaggerDefinition from './swagger.json';
import { Request, Response } from 'express-serve-static-core';
import QueryString from 'qs';
dotenv.config({ path: './.env' });
const app = express();
app.use('/assets', express.static(__dirname + '/assets'));
const swaggerDocument = {
info: {
title: 'COVID-19 API',
version: '1.0.0',
description: 'Public API for COVID-19 Data of India',
contact: {
name: 'Heet Vakharia',
email: '[email protected]',
},
servers: ['https://covidindiapublicapi.herokuapp.com/'],
},
basePath: '/',
host: 'https://covidindiapublicapi.herokuapp.com/',
swagger: '2.0',
};
app.use(cors());
app.use(
'/docs',
swaggerUi.serve,
swaggerUi.setup(swaggerDefinition, {
swaggerOptions: swaggerDocument,
customSiteTitle: 'Covid India',
customCss: '.swagger-ui .topbar { display: none }',
customfavIcon: './assets/favicon.ico',
}),
);
const pool = mysql.createPool({
host: process.env.MYSQL_ADDON_HOST,
database: process.env.MYSQL_ADDON_DB,
user: process.env.MYSQL_ADDON_USER,
password: process.env.MYSQL_ADDON_PASSWORD,
port: Number(process.env.MYSQL_ADDON_PORT),
uri: process.env.MYSQL_ADDON_URI,
});
const db = pool.promise();
const cache = new NodeCache({ stdTTL: 60 * 60 * 24 });
(async () => {
console.log('Adding Data');
await refreshData(db, cache);
})();
const day = 1000 * 60 * 60 * 24;
setInterval(async () => {
console.log('Refreshing');
await refreshData(db, cache);
}, day);
app.get('/', (req: Request, res: Response) => {
res.redirect('/docs');
});
// All States
app.get(
'/states',
async (
req: Request<{}, any, any, QueryString.ParsedQs, Record<string, any>>,
res: Response<any, Record<string, any>, number>,
) => {
let { min_date: minDate, max_date: maxDate } = req.query;
if (!minDate) {
minDate = moment().subtract(1, 'days').format('YYYY-MM-DD') as string;
}
if (!maxDate) {
maxDate = moment().format('YYYY-MM-DD') as string;
}
if (!(isDate(minDate as string) && isDate(maxDate as string))) {
return res.status(400).json({ error: 'Invalid Date' });
}
if (cache.has(`states-${minDate}-${maxDate}`)) {
return res.status(200).send(cache.get(`states-${minDate}-${maxDate}`));
}
const data = await db.query(
`SELECT * FROM state_cases WHERE date BETWEEN '${minDate}' AND '${maxDate}'`,
);
cache.set(`states-${minDate}-${maxDate}`, data[0], day);
res.status(200).send(data[0] as any);
},
);
// Get Data for a specific state by state code
app.get(
'/states/code/:state_code',
async (
req: Request<
{
state_code: string;
},
any,
any,
QueryString.ParsedQs,
Record<string, any>
>,
res: Response<any, Record<string, any>, number>,
) => {
let { min_date: minDate, max_date: maxDate } = req.query;
const stateCode = Number(req.params.state_code);
if (!minDate) {
minDate = moment().subtract(1, 'days').format('YYYY-MM-DD');
}
if (!maxDate) {
maxDate = moment().format('YYYY-MM-DD');
}
if (!(isDate(minDate as string) && isDate(maxDate as string))) {
return res.json({ error: 'Invalid Date' });
}
if (stateCode === NaN || stateCode < 1 || stateCode > 36) {
return res
.status(400)
.json({ error: 'Invalid State Code', state_code: stateCode });
}
const stateAbbrCheck = Object.values(StateCodeMap).find(
(v: [string | string[], number]) => v[1] === stateCode,
) as any;
if (!stateAbbrCheck) {
return res.status(400).json({ error: 'Invalid State Code' });
}
const stateAbbr = stateAbbrCheck[0] as string;
if (cache.has(`state_${stateAbbr}-${minDate}-${maxDate}`)) {
return res
.status(200)
.send(cache.get(`state_${stateAbbr}-${minDate}-${maxDate}`));
}
try {
const [data] = await db.query(
`SELECT * FROM state_cases WHERE state_code=${stateCode} AND (date BETWEEN '${minDate}' AND '${maxDate}')`,
);
console.log(minDate, maxDate);
cache.set(`state_${stateAbbr}-${minDate}-${maxDate}`, data, day);
return res.status(200).send(data);
} catch (err) {
return res.status(400).send({ error: 'Invalid State Code' });
}
},
);
// Get Data for a specific state by state abbr
app.get(
'/states/abbr/:state_abbr',
async (
req: Request<
{
state_abbr: string;
},
any,
any,
QueryString.ParsedQs,
Record<string, any>
>,
res: Response<any, Record<string, any>, number>,
) => {
let { min_date: minDate, max_date: maxDate } = req.query;
const stateAbbr: string = req.params.state_abbr;
if (!stateAbbr) {
res.status(400).json({ error: 'State Abbr Undefined' });
}
if (!minDate) {
minDate = moment().subtract(1, 'days').format('YYYY-MM-DD');
}
if (!maxDate) {
maxDate = moment().format('YYYY-MM-DD');
}
if (cache.has(`state_${stateAbbr}-${minDate}-${maxDate}`)) {
return res
.status(200)
.send(cache.get(`state_${stateAbbr}-${minDate}-${maxDate}`));
}
if (!(isDate(minDate as string) && isDate(maxDate as string))) {
return res.json({ error: 'Invalid Date' });
}
const [data] = await db.query(
`SELECT * FROM state_cases WHERE state_abbr LIKE '%${stateAbbr}%' AND (date BETWEEN '${minDate}' AND '${maxDate}')`,
);
cache.set(`state_${stateAbbr}-${minDate}-${maxDate}`, data, day);
res.status(200).send(data);
},
);
// Get Data for whole country
app.get(
'/country',
async (
req: Request<{}, any, any, QueryString.ParsedQs, Record<string, any>>,
res: Response<any, Record<string, any>, number>,
) => {
let { min_date: minDate, max_date: maxDate } = req.query;
if (!minDate) {
minDate = moment().subtract(1, 'days').format('YYYY-MM-DD');
}
if (!maxDate) {
maxDate = moment().format('YYYY-MM-DD');
}
if (cache.has(`country-${minDate}-${maxDate}`)) {
return res.status(200).send(cache.get(`country-${minDate}-${maxDate}`));
}
if (!(isDate(minDate as string) && isDate(maxDate as string))) {
return res.json({ error: 'Invalid Date' });
}
const [data] = await db.query(
`SELECT * FROM country_cases WHERE date BETWEEN '${minDate}' AND '${maxDate}'`,
);
cache.set(`country-${minDate}-${maxDate}`, data, day);
res.status(200).send(data);
},
);
// Port to listen on
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});