-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
gatsby-node.ts
299 lines (268 loc) · 8.66 KB
/
gatsby-node.ts
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { createOperations } from "./operations"
import { eventsApi } from "./events"
import {
CreateResolversArgs,
NodePluginArgs,
PluginOptionsSchemaArgs,
SourceNodesArgs,
} from "gatsby"
import { makeResolveGatsbyImageData } from "./resolve-gatsby-image-data"
import {
getGatsbyImageResolver,
IGatsbyGraphQLResolverArgumentConfig,
} from "gatsby-plugin-image/graphql-utils"
import { shiftLeft } from "shift-left"
import { pluginErrorCodes as errorCodes } from "./errors"
import { makeSourceFromOperation } from "./make-source-from-operation"
export { createSchemaCustomization } from "./create-schema-customization"
import { createNodeId } from "./node-builder"
import { JoiObject } from "joi"
export function pluginOptionsSchema({
Joi,
}: PluginOptionsSchemaArgs): JoiObject {
// @ts-ignore TODO: When Gatsby updates Joi version, update type
// Vague type error that we're not able to figure out related to isJoi missing
// Probably related to Joi being outdated
return Joi.object({
password: Joi.string().required(),
storeUrl: Joi.string()
.pattern(/^[a-z0-9-]+\.myshopify\.com$/)
.message(
`The storeUrl value should be your store's myshopify.com URL in the form "my-site.myshopify.com", without https or slashes`
)
.required(),
downloadImages: Joi.boolean(),
typePrefix: Joi.string()
.pattern(new RegExp(`(^[A-Z]w*)`))
.message(
`"typePrefix" can only be alphanumeric characters, starting with an uppercase letter`
)
.default(``),
shopifyConnections: Joi.array()
.default([])
.items(Joi.string().valid(`orders`, `collections`)),
salesChannel: Joi.string().default(
process.env.GATSBY_SHOPIFY_SALES_CHANNEL || ``
),
})
}
async function sourceAllNodes(
gatsbyApi: SourceNodesArgs,
pluginOptions: ShopifyPluginOptions
): Promise<void> {
const {
createProductsOperation,
createProductVariantsOperation,
createOrdersOperation,
createCollectionsOperation,
finishLastOperation,
completedOperation,
cancelOperationInProgress,
} = createOperations(pluginOptions, gatsbyApi)
const operations = [createProductsOperation, createProductVariantsOperation]
if (pluginOptions.shopifyConnections?.includes(`orders`)) {
operations.push(createOrdersOperation)
}
if (pluginOptions.shopifyConnections?.includes(`collections`)) {
operations.push(createCollectionsOperation)
}
const sourceFromOperation = makeSourceFromOperation(
finishLastOperation,
completedOperation,
cancelOperationInProgress,
gatsbyApi,
pluginOptions
)
for (const op of operations) {
await sourceFromOperation(op)
}
}
const shopifyNodeTypes = [
`ShopifyLineItem`,
`ShopifyProductMetafield`,
`ShopifyProductVariantMetafield`,
`ShopifyCollectionMetafield`,
`ShopifyOrder`,
`ShopifyProduct`,
`ShopifyCollection`,
`ShopifyProductImage`,
`ShopifyCollectionImage`,
`ShopifyProductFeaturedImage`,
`ShopifyProductVariant`,
`ShopifyProductVariantImage`,
`ShopifyProductVariantPricePair`,
`ShopifyProductFeaturedMediaPreviewImage`,
]
async function sourceChangedNodes(
gatsbyApi: SourceNodesArgs,
pluginOptions: ShopifyPluginOptions
): Promise<void> {
const {
incrementalProducts,
incrementalProductVariants,
incrementalOrders,
incrementalCollections,
finishLastOperation,
completedOperation,
cancelOperationInProgress,
} = createOperations(pluginOptions, gatsbyApi)
const { typePrefix = `` } = pluginOptions
const lastBuildTime = new Date(
gatsbyApi.store.getState().status.plugins?.[`gatsby-source-shopify`]?.[
`lastBuildTime${typePrefix}`
]
)
for (const nodeType of shopifyNodeTypes) {
gatsbyApi
.getNodesByType(`${typePrefix}${nodeType}`)
.forEach(node => gatsbyApi.actions.touchNode(node))
}
const operations = [
incrementalProducts(lastBuildTime),
incrementalProductVariants(lastBuildTime),
]
if (pluginOptions.shopifyConnections?.includes(`orders`)) {
operations.push(incrementalOrders(lastBuildTime))
}
if (pluginOptions.shopifyConnections?.includes(`collections`)) {
operations.push(incrementalCollections(lastBuildTime))
}
const sourceFromOperation = makeSourceFromOperation(
finishLastOperation,
completedOperation,
cancelOperationInProgress,
gatsbyApi,
pluginOptions
)
for (const op of operations) {
await sourceFromOperation(op)
}
const { fetchDestroyEventsSince } = eventsApi(pluginOptions)
const destroyEvents = await fetchDestroyEventsSince(lastBuildTime)
gatsbyApi.reporter.info(
`${destroyEvents.length} items have been deleted since ${lastBuildTime}`
)
if (destroyEvents.length) {
gatsbyApi.reporter.info(`Removing matching nodes from Gatsby`)
destroyEvents.forEach(e => {
const id = `${typePrefix}gid://shopify/${e.subject_type}/${e.subject_id}`
gatsbyApi.reporter.info(`Looking up node with ID: ${id}`)
const nodeId = createNodeId(id, gatsbyApi, pluginOptions)
const node = gatsbyApi.getNode(nodeId)
if (node) {
gatsbyApi.reporter.info(
`Removing ${node.internal.type}: ${node.id} with shopifyId ${e.subject_id}`
)
gatsbyApi.actions.deleteNode(node)
} else {
gatsbyApi.reporter.info(`Couldn't find node with ID: ${id}`)
}
})
}
}
export async function sourceNodes(
gatsbyApi: SourceNodesArgs,
pluginOptions: ShopifyPluginOptions
): Promise<void> {
const pluginStatus = gatsbyApi.store.getState().status.plugins?.[
`gatsby-source-shopify`
]
const lastBuildTime =
pluginStatus?.[`lastBuildTime${pluginOptions.typePrefix || ``}`]
if (lastBuildTime !== undefined) {
gatsbyApi.reporter.info(`Cache is warm, running an incremental build`)
await sourceChangedNodes(gatsbyApi, pluginOptions)
} else {
gatsbyApi.reporter.info(`Cache is cold, running a clean build`)
await sourceAllNodes(gatsbyApi, pluginOptions)
}
gatsbyApi.reporter.info(`Finished sourcing nodes, caching last build time`)
gatsbyApi.actions.setPluginStatus(
pluginStatus !== undefined
? {
...pluginStatus,
[`lastBuildTime${pluginOptions.typePrefix || ``}`]: Date.now(),
}
: {
[`lastBuildTime${pluginOptions.typePrefix || ``}`]: Date.now(),
}
)
}
export function createResolvers(
{ createResolvers, cache }: CreateResolversArgs,
{
downloadImages,
typePrefix = ``,
shopifyConnections = [],
}: ShopifyPluginOptions
): void {
if (!downloadImages) {
const args = {
placeholder: {
description: `Low resolution version of the image`,
type: `String`,
defaultValue: null,
} as IGatsbyGraphQLResolverArgumentConfig,
}
const imageNodeTypes = [
`ShopifyProductImage`,
`ShopifyProductVariantImage`,
`ShopifyProductFeaturedImage`,
`ShopifyProductFeaturedMediaPreviewImage`,
]
if (shopifyConnections.includes(`collections`)) {
imageNodeTypes.push(`ShopifyCollectionImage`)
}
const resolvers = imageNodeTypes.reduce((r, nodeType) => {
return {
...r,
[`${typePrefix}${nodeType}`]: {
gatsbyImageData: getGatsbyImageResolver(
makeResolveGatsbyImageData(cache),
args
),
},
}
}, {})
createResolvers(resolvers)
}
}
interface IErrorContext {
sourceMessage: string
}
const getErrorText = (context: IErrorContext): string => context.sourceMessage
export function onPreInit({ reporter }: NodePluginArgs): void {
reporter.setErrorMap({
[errorCodes.bulkOperationFailed]: {
text: getErrorText,
level: `ERROR`,
category: `USER`,
},
[errorCodes.apiConflict]: {
text: (): string => shiftLeft`
Your operation was canceled. You might have another production site for this Shopify store.
Shopify only allows one bulk operation at a time for a given shop, so we recommend that you
avoid having two production sites that point to the same Shopify store.
If the duplication is intentional, please wait for the other operation to finish before trying
again. Otherwise, consider deleting the other site or pointing it to a test store instead.
`,
level: `ERROR`,
category: `USER`,
},
/**
* If we don't know what it is, we haven't done our due
* diligence to handle it explicitly. That means it's our
* fault, so THIRD_PARTY indicates us, the plugin authors.
*/
[errorCodes.unknownSourcingFailure]: {
text: getErrorText,
level: `ERROR`,
category: `THIRD_PARTY`,
},
[errorCodes.unknownApiError]: {
text: getErrorText,
level: `ERROR`,
category: `THIRD_PARTY`,
},
})
}