-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
130 lines (111 loc) · 4.03 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
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
const express = require('express')
const app = express();
app.use(require('body-parser').json());
const { callAirtableRefresher } = require('./updateReferrals');
const { table } = require('./airtableBase');
const { readFile } = require('fs');
const { promisify } = require('util');
const readFileAsync = promisify(readFile);
const port = process.env.PORT || 3000;
const PIPE_NAME = process.env.PIPE_NAME || 'Pipeline'
// const assertEqual = (thing1, thing2) => { if (thing1 !== thing2) { throw new Error(`NOT EQUAL: ${thing1} !== ${thing2}`) } };
// URLS
const PIPE_URL = `/${PIPE_NAME}`;
const TEST_URL = `/${PIPE_NAME}/test`;
const AIRTABLE_REFRESH_URL = `/${PIPE_NAME}/airtable`;
const { atfield, KOBODATA } = require('./constants');
const AUTO_REFRESH_AIRTABLE = !['0', 'false'].includes(`${process.env.AUTO_REFRESH_AIRTABLE}`.toLowerCase());
const KOBO_DEBUG = (process.env.KOBO_DEBUG || 'false').toLowerCase() !== 'false';
if (KOBO_DEBUG) {
console.log("DEBUG MODE TRUE. heroku config: KOBO_DEBUG != 'false'")
}
const transformSubmission = (koboSubmission) => {
let timestampField = atfield('TODAY') || 'attoday';
let postData = {
[atfield('RECRUITED_BY_ID')]: koboSubmission[KOBODATA.ID_PARTICIPANT],
[atfield('REF_CARRIER')]: koboSubmission[KOBODATA.CARRIER] || '',
[atfield('REF_PHONE')]: koboSubmission[KOBODATA.PHONE_INCENTIVE] || '',
[timestampField]: koboSubmission[KOBODATA.TODAY] || new Date().toISOString(),
};
let records = [];
for (let i=1; i<=3; i++) {
let phoneVar = KOBODATA.INDEXED_PHONE.replace('#', i); // RECRUITMENT/RECRUIT1_PHONE
let nameVar = KOBODATA.INDEXED_NAME.replace('#', i); // RECRUITMENT/RECRUIT1_NAME
if (koboSubmission[phoneVar]) {
records.push({
...postData,
[atfield('PHONE')]: koboSubmission[phoneVar],
[atfield('NAME')]: koboSubmission[nameVar],
});
}
}
return records;
}
app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));
app.post(PIPE_URL, async (req, res) => {
if (KOBO_DEBUG) {
console.log('RECEIVED: ' + JSON.stringify(req.body));
}
const records = transformSubmission(req.body).map((rec) => { return { fields: rec } });
let created;
if (records.length > 0) {
created = table.create(records);
}
if (AUTO_REFRESH_AIRTABLE) {
try {
const results = await callAirtableRefresher();
res.send(results);
} catch (err) {
console.error('Error Refreshing Airtable:');
console.error(err);
}
} else {
const n = records.length
res.send({
message: `sent ${n} records`,
finished: [],
});
}
});
// TEST pages and ABOUT page
const templateFile = async (path, variables) => {
const txt = await readFileAsync(__dirname + '/' + path);
let respString = txt.toString();
Object.entries(variables).forEach( ([key, val]) => {
respString = respString.replace(new RegExp('\\${' + key + '}', 'g'), val);
});
return respString;
}
app.get(PIPE_URL, async (req, res) => {
const html = await templateFile('setup.html', { PIPE_URL });
res.send(html);
});
app.get(AIRTABLE_REFRESH_URL, async (req, res) => {
const AIRTABLE_REFRESHER_SCRIPT = (await readFileAsync(__dirname + '/airtableRefresher-page.js')).toString();
const html = await templateFile('airtableRefresher.html', {
AIRTABLE_REFRESHER_SCRIPT,
});
res.send(html);
});
app.post(AIRTABLE_REFRESH_URL, async (req, res) => {
try {
const { message, finished } = await callAirtableRefresher();
res.send(JSON.stringify({
message,
finished,
}));
} catch (err) {
console.error('Error Refreshing Airtable:');
console.error(err);
}
});
// TESTER available at /Pipeline/test
// It's basically a way to send mock data to the "transformSubmission()" function
app.post(TEST_URL, async (req, res) => {
return res.send(JSON.stringify(transformSubmission(req.body)));
});
app.get(TEST_URL, async (req, res) => {
const html = await templateFile('tester.html', { TEST_URL, PIPE_URL });
res.send(html);
});
app.listen(port, () => console.log(`App listening at http://localhost:${port}`))