-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.js
51 lines (42 loc) · 1.28 KB
/
handler.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
if (process.env.NODE_ENV === 'test') {
// eslint-disable-next-line
require('babel-plugin-require-context-hook/register')();
}
const RESOURCE_MAP = {};
function importAll(r) {
r.keys().forEach((key) => {
RESOURCE_MAP[key.replace('./', '').replace('.js', '')] = r(key);
});
}
importAll(require.context('./query', true, /\.js$/));
importAll(require.context('./mutation', true, /\.js$/));
const formatResult = (r) => {
// Assign "pk" as "id" to match GraphQL schema
let result = r;
if (!result.id && result.pk) {
result.id = result.pk;
}
// For arrays, check all pk's
if (typeof result === 'object' && result.length) {
result = result.map((i) => {
if (!i.id && i.pk) {
// eslint-disable-next-line no-param-reassign
i.id = i.pk;
}
return i;
});
}
return result;
};
// eslint-disable-next-line import/prefer-default-export
export async function request(event) {
return Promise.resolve()
.then(async () => {
if (event.field && typeof RESOURCE_MAP[event.field].default !== 'undefined') {
const resource = RESOURCE_MAP[event.field].default;
const result = formatResult(await resource(event));
return result;
}
throw new Error(`Unknown event ${event.field} // ${RESOURCE_MAP}`);
});
}