-
Notifications
You must be signed in to change notification settings - Fork 7
/
gatsby-node.js
69 lines (60 loc) · 1.84 KB
/
gatsby-node.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
const Sheets = require("node-sheets").default;
const createNodeHelpers = require("gatsby-node-helpers").default;
const camelCase = require("camelcase");
exports.sourceNodes = async ({ actions, createNodeId }, pluginOptions) => {
const { createNode } = actions;
const {
spreadsheetId,
spreadsheetName = "",
typePrefix = "GoogleSpreadsheet",
credentials,
filterNode = () => true,
mapNode = node => node
} = pluginOptions;
const { createNodeFactory } = createNodeHelpers({
typePrefix
});
const gs = new Sheets(spreadsheetId);
if (credentials) {
await gs.authorizeJWT(credentials);
}
const promises = (await gs.getSheetsNames()).map(async sheetTitle => {
const tables = await gs.tables(sheetTitle);
const { rows } = tables;
const buildNode = createNodeFactory(
camelCase(`${spreadsheetName} ${sheetTitle}`)
);
rows
.map(toNode)
.filter(filterNode)
.map(mapNode)
.forEach((node, i) => {
const hasProperties = Object.values(node).some(value => value !== null);
if (hasProperties) {
createNode({
...buildNode(node),
id: createNodeId(
`${typePrefix} ${spreadsheetName} ${sheetTitle} ${i}`
)
});
}
});
});
return Promise.all(promises);
};
function toNode(row) {
return Object.entries(row).reduce((obj, [key, cell]) => {
if (key === undefined || key === "undefined") {
return obj;
}
// `node-sheets` adds default values for missing numbers and dates, by checking
// for the precense of `stringValue` (the formatted value), we can ensure that
// the value actually exists.
const value =
typeof cell === "object" && cell.stringValue !== undefined
? cell.value
: null;
obj[camelCase(key)] = value;
return obj;
}, {});
}