-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
116 lines (101 loc) · 2.78 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
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
const {
getNamesDatesLists,
getListOverview,
isObject,
getReviews,
getBestSellersHistory,
getIdentifier,
getLists,
} = require("./utils")
const {
PLUGIN_NAME,
TYPE_LISTS,
TYPE_OVERVIEW,
TYPE_REVIEWS,
TYPE_BEST_SELLERS_HISTORY,
TYPE_DATE_LIST,
TYPE_NAMES_LIST,
TYPES,
} = require("./constants")
exports.sourceNodes = async (
{ actions, createNodeId, createContentDigest, reporter },
options
) => {
const { type, token } = options
if (!token) {
reporter.warn(`Unable to use ${PLUGIN_NAME}: API token is missing`)
return
}
if (!type || !TYPES.includes(type)) {
reporter.info(
`\`type\` not valid for ${PLUGIN_NAME}. Defaulting to \`type: list\` `
)
}
const { createNode } = actions
let data
let identifierPrefix = "nytimes"
let nodeType
switch (type) {
case TYPE_LISTS:
identifierPrefix = `${identifierPrefix}-lists`
nodeType = "TimesBooksList"
data = await getLists(options, reporter)
break
case TYPE_OVERVIEW:
identifierPrefix = `${identifierPrefix}-overview`
nodeType = "TimesBooksListOverview"
data = await getListOverview(options, reporter)
break
case TYPE_REVIEWS:
identifierPrefix = `${identifierPrefix}-review`
nodeType = "TimesBooksReview"
data = await getReviews(options, reporter)
break
case TYPE_BEST_SELLERS_HISTORY:
identifierPrefix = `${identifierPrefix}-best-seller`
nodeType = "TimesBooksBestSellerHistory"
data = await getBestSellersHistory(options, reporter)
break
case TYPE_DATE_LIST:
identifierPrefix = `${identifierPrefix}-date-list`
nodeType = "TimesBooksDateList"
data = await getNamesDatesLists(options, reporter)
break
case TYPE_NAMES_LIST:
identifierPrefix = `${identifierPrefix}-list-name`
nodeType = "TimesBooksListName"
data = await getNamesDatesLists(options, reporter)
break
default:
reporter.warn(`${PLUGIN_NAME}: type of "${type}" not recognized`)
break
}
const processNode = node =>
Object.assign({}, node, {
id: createNodeId(`${identifierPrefix}-${getIdentifier(type, node)}`),
parent: null,
children: [],
internal: {
type: nodeType,
content: JSON.stringify(node),
contentDigest: createContentDigest(node),
},
})
return new Promise(function(resolve) {
let processedNode
if (data && data.length) {
data.forEach(datum => {
processedNode = processNode(datum)
createNode(processedNode)
})
} else if (isObject(data)) {
processedNode = processNode(data)
createNode(processedNode)
} else {
reporter.info(
`No data returned from ${PLUGIN_NAME}, no Gatsby nodes created.`
)
}
resolve()
})
}