-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
96 lines (84 loc) · 2.52 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
'use strict';
const pushToAirtable = require('./src/pushToAirtable');
const validate = require('./site-ingestion-schema/validator');
console.log('Loading site ingestion API');
exports.handler = async (event) => {
console.log(`Request: ${JSON.stringify(event)}`);
if (event.path !== '/form-upload' && event.path !== '/upload-site') {
return {
statusCode: 404,
body: JSON.stringify({
error: 'Unsupported endpoint'
})
};
}
if (!event.body || Object.keys(event.body).length === 0) {
return {
statusCode: 400,
body: JSON.stringify({
error: 'Empty payload'
})
};
}
let sites;
let body;
try {
body = JSON.parse(event.body);
// add workaround for FormAssembly data
if (event.path === '/form-upload') {
sites = [body];
} else if (event.path === '/upload-site') {
if (!body.data || !Array.isArray(body.data) || body.data.length === 0) {
return {
statusCode: 400,
body: JSON.stringify({
error: 'No data array provided'
})
};
}
sites = body.data;
}
} catch (e) {
console.log(`Invalid payload: ${body}`);
return {
statusCode: 400,
body: JSON.stringify({
error: 'Invalid payload'
})
};
}
// check if sites conform to schema
const [isValid, errorMsg] = validate(sites);
if (!isValid) {
return {
statusCode: 400,
body: JSON.stringify({
error: errorMsg
})
};
}
// attempt to push to Airtable
let sitesAdded; let siteDetailsAdded;
let email; let password;
try {
email = await body.email;
console.log('THE TEST PASSWORD LOOKS LIKE', email);
password = await !!body.password ? body.password : null;
[sitesAdded, siteDetailsAdded] = await pushToAirtable(sites, email, password);
} catch (err) {
console.log(err);
return {
statusCode: 500,
body: JSON.stringify({
error: `${err.name}: ${err.message}`
})
};
}
const response = {
statusCode: 200,
body: JSON.stringify({
message: `Added ${sitesAdded} new sites and ${siteDetailsAdded} new site details`
})
};
return response;
};