-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAPIAggregation.js
More file actions
304 lines (265 loc) · 8.64 KB
/
Copy pathAPIAggregation.js
File metadata and controls
304 lines (265 loc) · 8.64 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
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
require('dotenv').config();
const fs = require('fs');
const mongoose = require('mongoose');
const db = require('./models');
const MONGODB_URI = process.env.MONGODB_URI;
const moment = require('moment');
const axios = require('axios');
const SOCRATA_API_SECRET = process.env.SOCRATA_API_SECRET;
const SOCRATA_API_KEY = process.env.SOCRATA_API_KEY;
const AggregateByBuilding = require('./AggregateByBuilding');
// const { get } = require('mongoose');
// const TOKEN = process.env.TOKEN;
const includedCounties = [
'063', //Clayton
'067', //Cobb
'089', //DeKalb
'121', //Fulton
'135' //Gwinnett
];
const endDate = '02/06/2022';
mongoose
.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('DB Connected');
})
.catch(err => {
console.log('DB Connection ERROR: ', err);
});
const sortByDate = dateField => {
return (a, b) => {
const dateA = new Date(a[dateField]).getTime();
const dateB = new Date(b[dateField]).getTime();
return dateA > dateB ? -1 : 1;
};
};
const fetchData = async () => {
const gaTechData = [];
const fultonData = [];
await axios
.get(
'https://sharefulton.fultoncountyga.gov/resource/qh59-mhjw.json?$limit=50000',
{
auth: { username: SOCRATA_API_KEY, password: SOCRATA_API_SECRET }
}
)
.then(({ data }) => {
data
.filter(item => includedCounties.includes(item.countyfp10))
.sort(sortByDate('filedate'))
.forEach(item =>
fultonData.push({ ...item, totalfilings: Number(item.totalfilings) })
);
})
.catch(err => console.log('Error Fetching Fulton Data: ', err));
await axios
.get(
'https://evictions.design.gatech.edu/rest/atlanta_metro_area_tracts?select=id,filedate,tractid,countyfp10,totalfilings,totalansweredfilings'
)
.then(({ data }) => {
data
.filter(item => includedCounties.includes(item.countyfp10))
.sort(sortByDate('filedate'))
.forEach(item =>
gaTechData.push({
...item,
totalfilings: Number(item.totalfilings),
totalansweredfilings: Number(item.totalansweredfilings)
})
);
})
.catch(err => console.log('Error Fetching GT Data: ', err));
return [gaTechData, fultonData];
};
const aggregateTractMonth = ([fromGaTech, fromFulton]) => {
const filteredArr = fromGaTech.filter(({countyfp10}) => countyfp10 !== '121');
const dataArr = [...filteredArr, ...fromFulton].sort(sortByDate('filedate'));
const obj = {};
dataArr
.filter(({filedate}) =>
new Date(filedate).getTime() >= new Date('1/1/2020').getTime() &&
new Date(filedate).getTime() <= new Date(endDate).getTime()
)
.forEach(({filedate, totalfilings, tractid, countyfp10}) => {
const filingMonth = moment(filedate)
.startOf('month')
.format('MM/DD/YYYY');
const key = tractid;
const duringPandemic = new Date(filedate) >= new Date('04/01/2020');
if (obj[key]) {
if (obj[key].FilingsByMonth[filingMonth]) {
obj[key].FilingsByMonth[filingMonth] += totalfilings;
} else {
obj[key].FilingsByMonth[filingMonth] = totalfilings
}
} else {
obj[key] = {
TractID: tractid,
CountyID: countyfp10,
FilingsByMonth : {
[filingMonth] : totalfilings,
'During the Pandemic' : 0
}
}
}
if (duringPandemic) {
obj[key].FilingsByMonth['During the Pandemic'] += totalfilings
}
});
return Object.values(obj);
};
const aggregateCounty = ([fromGaTech, fromFulton], type) => {
const endDateOfFultonFromGaTech = fromGaTech
.filter(obj => obj.countyfp10 === '121')
.sort(sortByDate('filedate'))[0].filedate;
const dataArr = [
...fromGaTech,
...fromFulton.filter(
item =>
new Date(item.filedate).getTime() >
new Date(endDateOfFultonFromGaTech).getTime()
)
];
// Aggregate Baseline Data
const baselineObj = {};
dataArr
.filter(
({ filedate }) =>
new Date(filedate).getTime() >= new Date('1/1/2019').getTime() &&
new Date(filedate).getTime() < new Date('1/1/2020').getTime()
)
.forEach(({ filedate, countyfp10, totalfilings }) => {
const date =
type === 'Month'
? moment(filedate).startOf(type.toLowerCase()).format('MM/DD')
: moment(filedate).week();
const key = `${countyfp10}-${date}`;
baselineObj[key]
? (baselineObj[key] = baselineObj[key] += totalfilings)
: (baselineObj[key] = totalfilings ? totalfilings : 0);
const totalKey = `999-${date}`;
baselineObj[totalKey]
? (baselineObj[totalKey] = baselineObj[totalKey] += totalfilings)
: (baselineObj[totalKey] = totalfilings ? totalfilings : 0);
});
const obj = {};
dataArr
.filter(
({ filedate }) =>
// new Date(filedate).getTime() >= new Date('1/1/2020').getTime()
new Date(filedate).getTime() >= new Date('1/1/2020').getTime() &&
new Date(filedate).getTime() <= new Date(endDate).getTime()
)
.forEach(({ filedate, countyfp10, totalfilings, totalansweredfilings }) => {
const date = moment(filedate)
.startOf(type.toLowerCase())
.format('MM/DD/YYYY');
const key = `${countyfp10}-${date}`;
const baselineKey = `${countyfp10}-${
type === 'Month'
? moment(date).startOf(type.toLowerCase()).format('MM/DD')
: moment(date).week()
}`;
obj[key]
? (obj[key] = {
...obj[key],
TotalFilings: (obj[key].TotalFilings += totalfilings),
AnsweredFilings: totalansweredfilings
? (obj[key].AnsweredFilings += totalansweredfilings)
: obj[key].AnsweredFilings
})
: (obj[key] = {
[`Filing${type}`]: date,
CountyID: countyfp10,
TotalFilings: totalfilings,
AnsweredFilings: totalansweredfilings ? totalansweredfilings : 0,
BaselineFilings: baselineObj[baselineKey]
});
const totalKey = `999-${date}`;
const totalBaselineKey = `999-${baselineKey.split('-')[1]}`;
obj[totalKey]
? (obj[totalKey] = {
...obj[totalKey],
TotalFilings: (obj[totalKey].TotalFilings += totalfilings),
AnsweredFilings: totalansweredfilings
? (obj[totalKey].AnsweredFilings += totalansweredfilings)
: obj[totalKey].AnsweredFilings
})
: (obj[totalKey] = {
[`Filing${type}`]: date,
CountyID: '999',
TotalFilings: totalfilings,
AnsweredFilings: totalansweredfilings ? totalansweredfilings : 0,
BaselineFilings: baselineObj[totalBaselineKey]
});
});
return Object.values(obj);
};
const getBackUpData = async () => {
// const backup = {
// tractmonth: null,
// countymonth: null,
// countyweek: null
// };
await db.tractMonth
.find({})
.then(data => fs.writeFile(`./data/backupTractMonth.json`, JSON.stringify(data), err => console.log(err || 'Backup File Saved for Tract Month')))
// backup.tractmonth = data)
.catch(err => console.log(err));
await db.countyMonth
.find({})
.then(data => fs.writeFile(`./data/backupCountyMonth.json`, JSON.stringify(data), err => console.log(err || 'Backup File Saved for County Month')))
// backup.countymonth = data)
.catch(err => console.log(err));
await db.countyWeek
.find({})
.then(data => fs.writeFile(`./data/backupCountyWeek.json`, JSON.stringify(data), err => console.log(err || 'Backup File Saved for County Week')))
// backup.countyweek = data)
.catch(err => console.log(err));
// return backup;
}
getBackUpData()
.then(() =>
fetchData()
.then(data => {
//Add Archiver and Validator
Promise.allSettled([
db.tractMonth
.deleteMany({})
.then(() =>
db.tractMonth
.insertMany(aggregateTractMonth(data))
.then(() => console.log('Tract Month Updated on DB'))
.catch(err => {
console.log(err);
})
)
.catch(err => console.log(err)),
db.countyMonth
.deleteMany({})
.then(() =>
db.countyMonth
.insertMany(aggregateCounty(data, 'Month'))
.then(() => console.log('County Month Updated on DB'))
.catch(err => console.log(err))
)
.catch(err => console.log(err)),
db.countyWeek
.deleteMany({})
.then(() =>
db.countyWeek
.insertMany(aggregateCounty(data, 'Week'))
.then(() => console.log('County Week Updated on DB'))
.catch(err => console.log(err))
)
.catch(err => console.log(err))
])
.then(() => {
AggregateByBuilding();
console.log('Data successfully updated')
})
.catch(err => console.log('Error Settling Promise: ', err));
})
.catch(err => console.log('Error Fetching Data: ', err))
)
.catch(err => console.log('Error Getting Backup Data: ', err))