-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trawl.js
49 lines (47 loc) · 1.44 KB
/
trawl.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
const superagent = require('superagent'),
{ endpoints } = require('../../config'),
{ API } = require('../../../../constants'),
ppKeys = ['CONGRESS_KEY', 'CONGRESS_ALTERNATE_KEY'];
require('dotenv').config();
module.exports = {
trawl: async (fn, param) => {
const tryCallProPublica = async (k) => {
const response = await superagent
.get(
process.env.REACT_APP_PROPUBLICA_BASEURI +
process.env.REACT_APP_PROPUBLICA_CONGRESS_SUBDIR +
endpoints(fn, param)
)
.set({
'Content-Type': 'application/json',
'X-API-Key': API.PROPUBLICA[ppKeys[k]],
});
const schema = {
// the API has inconsistent data structure. 'recent' is not wrapped in an array
recent: JSON.parse(response.text).results,
pols: JSON.parse(response.text).results[0],
default: await JSON.parse(response.text).results[0],
};
return schema[fn] || schema.default;
};
try {
return await tryCallProPublica(0);
} catch (err) {
console.error(
'Controller congress service trawl.js caught error: ' +
err +
' - Retrying with alt API key...'
);
try {
return await tryCallProPublica(1);
} catch (err) {
console.error(
'Controller congress service trawl.js caught error: ' +
err +
' - All keys tried.'
);
return err;
}
}
},
};