-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlily-client.js
92 lines (75 loc) · 2.42 KB
/
lily-client.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
const axios = require('axios');
const { INFO, ERROR, WARNING } = require('./logs');
const { DB } = require('./db');
let db = new DB();
class LilyClient {
constructor(api, token, start_date) {
this.api = api;
this.token = token;
this.start_date = start_date;
}
async get(url) {
let response = undefined;
try {
if (this.token) {
response = await axios.get(url, {
headers: {
Authorization: `Bearer ${this.token}`,
},
timeout: 30000 //30 sec
});
} else {
response = await axios.get(url, {timeout: 30000});
}
} catch (e) {
ERROR(`Get ${url} -> error: ${e}`);
}
return response;
}
async getDay(day) {
let data = (await this.get(this.api + `?state_date=${day}`))?.data?.data;
if (data?.length > 0) {
await db.save_lily_data(data);
}
return data?.length;
}
addDays(d, days) {
var date = new Date(d);
date.setDate(date.getDate() + days);
return date;
}
getSeries(start, end) {
const startDate = new Date(start);
const stopDate = new Date(end);
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push((new Date(currentDate)).toISOString().split('T')[0]);
currentDate = this.addDays(currentDate, 1);
}
return dateArray;
}
async update() {
let endDate = (new Date());
endDate.setDate(endDate.getDate() - 1);
endDate = endDate.toISOString().split('T')[0];
let startDate = await db.get_lily_start_date();
if (!startDate) {
startDate = this.start_date;
} else {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate() + 1);
startDate = startDate.toISOString().split('T')[0];
}
let series = this.getSeries(startDate, endDate);
INFO(`[Lily_update] get data for : ${series.length} days`);
for (const d of series) {
INFO(`[Lily_update] get data for : ${d}`);
let items = await this.getDay(d);
INFO(`[Lily_update] get data for : ${d} done, ${items} items`);
}
}
}
module.exports = {
LilyClient
};