This repository has been archived by the owner on Mar 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
createResolvers.js
65 lines (56 loc) · 1.78 KB
/
createResolvers.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
const sanitize = require("./sanitize");
// Takes an airtable schema and returns GraphQL resolvers.
module.exports = (airtableSchema, api, columnSupport) => {
const fetchRecord = (api, table, id) =>
new Promise((resolve, reject) => {
api(table).find(id, (err, record) => {
if (err) {
reject(err);
}
resolve(record);
});
});
const resolversForTable = (table, api) => {
return table.columns.reduce((resolvers, column) => {
let columnBuilder = columnSupport[column.type];
if (!columnBuilder || !columnBuilder.resolver) {
columnBuilder = columnSupport['text']
}
resolvers[sanitize.toField(column.name)] = columnBuilder.resolver(column, api);
return resolvers;
}, {});
};
const resolverForAll = (table, api) => () =>
new Promise((resolve, reject) => {
let results = [];
api(table.name)
.select()
.eachPage(
(records, nextPage) => {
results = [...results, ...records];
nextPage();
},
err => {
resolve(results);
}
);
});
const resolverForSingle = (table, api) => (_, args) => {
return fetchRecord(api, table.name, args.id);
};
const resolvers = {
Query: {}
};
resolvers.Query.tables = () => {
return airtableSchema.tables.map(t => t.name);
};
airtableSchema.tables.forEach(table => {
const all = sanitize.plural(sanitize.toField(table.name));
resolvers.Query[all] = resolverForAll(table, api);
const single = sanitize.singular(sanitize.toField(table.name));
resolvers.Query[single] = resolverForSingle(table, api);
const typeName = sanitize.toType(table.name);
resolvers[typeName] = resolversForTable(table, api);
});
return resolvers;
};