-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-node.js
303 lines (255 loc) · 6.64 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
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
300
301
302
303
const axios = require('axios');
const { object, string } = require('yup');
const { ProductNode } = require('./nodes');
const { TYPE_PREFIX, PRODUCT } = require('./constants');
const { PRODUCT_FRAGMENT } = require('./fragments');
const PLUGIN_CONFIG_SCHEMA = object({
shopName: string().required(),
accessToken: string().required(),
adminToken: string().required(),
});
function createClients(options) {
const { shopName, accessToken, adminToken } = options;
const storefrontClient = axios.create({
baseURL: `https://${shopName}/api/2020-04/graphql`,
method: 'post',
headers: {
'X-Shopify-Storefront-Access-Token': accessToken,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});
const adminClient = axios.create({
baseURL: `https://${shopName}/admin/api/2020-04/graphql.json`,
method: 'post',
headers: {
'X-Shopify-Access-Token': adminToken,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});
return { storefrontClient, adminClient };
}
const PRODUCT_UPDATES_QUERY = `
query($first: Int!, $after: String, $query: String) {
products(
first: $first
after: $after
query: $query
sortKey: UPDATED_AT
reverse: true
) {
edges {
cursor
node {
__typename
id
storefrontId
published: publishedOnCurrentPublication
updatedAt
}
}
pageInfo {
hasNextPage
}
}
}
`;
async function fetchAdminProductUpdates({ adminClient }, variables) {
const { data } = await adminClient({
data: {
query: PRODUCT_UPDATES_QUERY,
variables,
}
});
return data.data.products;
}
async function* adminProductUpdates(clients, since) {
const hourSlug = since.toISOString().substring(0, 13);
const query = `updated_at:>${hourSlug}`;
let { edges, pageInfo: { hasNextPage } } = await fetchAdminProductUpdates(clients, {
first: 250,
query,
});
while (1) {
if (!edges.length) {
break;
}
const batch = [];
while (1) {
if (batch.length === 50 || !edges.length) {
break;
}
const edge = edges.shift();
if (new Date(edge.node.updatedAt) < since) {
yield batch;
return;
}
batch.push(edge);
}
yield batch;
if (edges.length < 50 && hasNextPage) {
({ edges, pageInfo: { hasNextPage } } = await fetchAdminProductUpdates(clients, {
first: 250,
query,
after: edges.length ? edges[edges.length - 1].cursor : batch[batch.length - 1].cursor,
}));
}
}
}
const PRODUCT_DELETES_QUERY = `
query ($first: Int!, $after: String, $query: String) {
deletionEvents(
first: $first,
after: $after,
query: $query,
subjectTypes: [PRODUCT],
sortKey: CREATED_AT
reverse: true
) {
edges {
cursor
node {
occurredAt
subjectId
}
}
pageInfo {
hasNextPage
}
}
}
`;
async function fetchAdminProductDeletes({ adminClient }, variables) {
const { data } = await adminClient({
data: {
query: PRODUCT_DELETES_QUERY,
variables,
}
});
return data.data.deletionEvents;
}
async function* adminProductDeletes(clients, since) {
const hourSlug = since.toISOString().substring(0, 13);
const query = `occurred_at:>${hourSlug}`;
let { edges, pageInfo: { hasNextPage } } = await fetchAdminProductDeletes(clients, {
first: 250,
query,
});
while (1) {
if (!edges.length) {
break;
}
const batch = [];
while (1) {
if (batch.length === 50 || !edges.length) {
break;
}
const edge = edges.shift();
if (new Date(edge.node.occurredAt) < since) {
yield batch;
return;
}
batch.push(edge);
}
yield batch;
if (edges.length < 50 && hasNextPage) {
({ edges, pageInfo: { hasNextPage } } = await fetchAdminProductDeletes(clients, {
first: 250,
query,
after: edges.length ? edges[edges.length - 1].cursor : batch[batch.length - 1].cursor,
}));
}
}
}
const PRODUCTS_BY_IDS_QUERY = `
${PRODUCT_FRAGMENT}
query ($ids: [ID!]!) {
nodes(ids: $ids) {
...on Product {
...ProductFragment
}
}
}
`;
async function fetchStorefrontProducts({ storefrontClient }, ids) {
const { data } = await storefrontClient({
data: {
query: PRODUCTS_BY_IDS_QUERY,
variables: {
ids,
},
}
});
return data.data.nodes;
}
async function* productEventsSince(clients, since) {
for await (let deletedProductEdges of adminProductDeletes(clients, since)) {
for (edge of deletedProductEdges) {
yield {
type: 'delete',
id: Buffer.from(edge.node.subjectId).toString('base64'),
};
}
}
let published = []; // @todo batch in 50s - this array could get large right now
for await (let updatedProductEdges of adminProductUpdates(clients, since)) {
for (edge of updatedProductEdges) {
if (edge.node.published) {
published.push(edge.node.storefrontId);
} else {
yield {
type: 'delete',
id: edge.node.storefrontId,
};
}
}
}
while(published.length) {
const batch = published.splice(0, 50);
const products = await fetchStorefrontProducts(clients, batch);
for (product of products) {
yield {
type: 'update',
product,
};
}
}
}
async function sourceNodes(
args,
pluginOptions
) {
const { actions, getNode, getNodesByType, cache } = args;
const { createNode, touchNode, deleteNode } = actions;
const options = await PLUGIN_CONFIG_SCHEMA.validate(pluginOptions);
const clients = createClients(options);
const lastFetched = await cache.get('gastby-source-crane-timestamp');
if (lastFetched) {
getNodesByType(`${TYPE_PREFIX}${PRODUCT}`).forEach(node => touchNode({ nodeId: node.id }));
}
// Add extra 5 minutes because shopify sometimes takes a while to publish updates
const since = lastFetched ? new Date(lastFetched - 5 * 60 * 1000) : new Date('1900-01-01T00:00:00Z');
const startedAt = Date.now();
for await (let event of productEventsSince(clients, since)) {
switch (event.type) {
case 'update': {
const node = ProductNode(event.product);
createNode(node);
break;
}
case 'delete': {
const node = getNode(`${TYPE_PREFIX}__${PRODUCT}__${event.id}`);
if (!node) {
break;
}
deleteNode({
node,
})
break;
}
}
}
await cache.set('gastby-source-crane-timestamp', startedAt);
}
exports.sourceNodes = sourceNodes;