This repository has been archived by the owner on Apr 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 390
/
register.ts
520 lines (446 loc) · 12.9 KB
/
register.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import {graphqlClientClass, GraphqlClient} from '../clients/admin';
import {InvalidDeliveryMethodError, ShopifyError} from '../error';
import {logger} from '../logger';
import {privacyTopics} from '../types';
import {ConfigInterface} from '../base-types';
import {Session} from '../session/session';
import {addHostToCallbackUrl, getHandlers, handlerIdentifier} from './registry';
import {queryTemplate} from './query-template';
import {
WebhookRegistry,
RegisterReturn,
WebhookHandler,
WebhookCheckResponse,
DeliveryMethod,
WebhookCheckResponseNode,
WebhookOperation,
RegisterResult,
RegisterParams,
} from './types';
interface RegisterTopicParams {
config: ConfigInterface;
session: Session;
topic: string;
existingHandlers: WebhookHandler[];
handlers: WebhookHandler[];
}
interface RunMutationsParams {
config: ConfigInterface;
client: GraphqlClient;
topic: string;
handlers: WebhookHandler[];
operation: WebhookOperation;
}
interface RunMutationParams {
config: ConfigInterface;
client: GraphqlClient;
topic: string;
handler: WebhookHandler;
operation: WebhookOperation;
}
export function register(
config: ConfigInterface,
webhookRegistry: WebhookRegistry,
) {
return async function register({
session,
}: RegisterParams): Promise<RegisterReturn> {
const log = logger(config);
log.info('Registering webhooks', {shop: session.shop});
const registerReturn: RegisterReturn = Object.keys(webhookRegistry).reduce(
(acc: RegisterReturn, topic) => {
acc[topic] = [];
return acc;
},
{},
);
const existingHandlers = await getExistingHandlers(config, session);
log.debug(
`Existing topics: [${Object.keys(existingHandlers).join(', ')}]`,
{shop: session.shop},
);
for (const topic in webhookRegistry) {
if (!Object.prototype.hasOwnProperty.call(webhookRegistry, topic)) {
continue;
}
if (privacyTopics.includes(topic)) {
continue;
}
registerReturn[topic] = await registerTopic({
config,
session,
topic,
existingHandlers: existingHandlers[topic] || [],
handlers: getHandlers(webhookRegistry)(topic),
});
// Remove this topic from the list of existing handlers so we have a list of leftovers
delete existingHandlers[topic];
}
// Delete any leftover handlers
for (const topic in existingHandlers) {
if (!Object.prototype.hasOwnProperty.call(existingHandlers, topic)) {
continue;
}
const GraphqlClient = graphqlClientClass({config});
const client = new GraphqlClient({session});
registerReturn[topic] = await runMutations({
config,
client,
topic,
handlers: existingHandlers[topic],
operation: WebhookOperation.Delete,
});
}
return registerReturn;
};
}
async function getExistingHandlers(
config: ConfigInterface,
session: Session,
): Promise<WebhookRegistry> {
const GraphqlClient = graphqlClientClass({config});
const client = new GraphqlClient({session});
const existingHandlers: WebhookRegistry = {};
let hasNextPage: boolean;
let endCursor: string | null = null;
do {
const query = buildCheckQuery(endCursor);
const response = await client.request<WebhookCheckResponse>(query);
response.data?.webhookSubscriptions?.edges.forEach((edge) => {
const handler = buildHandlerFromNode(edge);
if (!existingHandlers[edge.node.topic]) {
existingHandlers[edge.node.topic] = [];
}
existingHandlers[edge.node.topic].push(handler);
});
endCursor = response.data?.webhookSubscriptions?.pageInfo.endCursor!;
hasNextPage = response.data?.webhookSubscriptions?.pageInfo.hasNextPage!;
} while (hasNextPage);
return existingHandlers;
}
function buildCheckQuery(endCursor: string | null) {
return queryTemplate(TEMPLATE_GET_HANDLERS, {
END_CURSOR: JSON.stringify(endCursor),
});
}
function buildHandlerFromNode(edge: WebhookCheckResponseNode): WebhookHandler {
const endpoint = edge.node.endpoint;
let handler: WebhookHandler;
switch (endpoint.__typename) {
case 'WebhookHttpEndpoint':
handler = {
deliveryMethod: DeliveryMethod.Http,
callbackUrl: endpoint.callbackUrl,
// This is a dummy for now because we don't really care about it
callback: async () => {},
};
break;
case 'WebhookEventBridgeEndpoint':
handler = {
deliveryMethod: DeliveryMethod.EventBridge,
arn: endpoint.arn,
};
break;
case 'WebhookPubSubEndpoint':
handler = {
deliveryMethod: DeliveryMethod.PubSub,
pubSubProject: endpoint.pubSubProject,
pubSubTopic: endpoint.pubSubTopic,
};
break;
}
// Set common fields
handler.id = edge.node.id;
handler.includeFields = edge.node.includeFields;
handler.metafieldNamespaces = edge.node.metafieldNamespaces;
// Sort the array fields to make them cheaper to compare later on
handler.includeFields?.sort();
handler.metafieldNamespaces?.sort();
return handler;
}
async function registerTopic({
config,
session,
topic,
existingHandlers,
handlers,
}: RegisterTopicParams): Promise<RegisterResult[]> {
let registerResults: RegisterResult[] = [];
const {toCreate, toUpdate, toDelete} = categorizeHandlers(
config,
existingHandlers,
handlers,
);
const GraphqlClient = graphqlClientClass({config});
const client = new GraphqlClient({session});
let operation = WebhookOperation.Create;
registerResults = registerResults.concat(
await runMutations({config, client, topic, operation, handlers: toCreate}),
);
operation = WebhookOperation.Update;
registerResults = registerResults.concat(
await runMutations({config, client, topic, operation, handlers: toUpdate}),
);
operation = WebhookOperation.Delete;
registerResults = registerResults.concat(
await runMutations({config, client, topic, operation, handlers: toDelete}),
);
return registerResults;
}
type HandlersByKey = Record<string, WebhookHandler>;
function categorizeHandlers(
config: ConfigInterface,
existingHandlers: WebhookHandler[],
handlers: WebhookHandler[],
) {
const handlersByKey = handlers.reduce((acc: HandlersByKey, value) => {
acc[handlerIdentifier(config, value)] = value;
return acc;
}, {});
const existingHandlersByKey = existingHandlers.reduce(
(acc: HandlersByKey, value) => {
acc[handlerIdentifier(config, value)] = value;
return acc;
},
{},
);
const toCreate: HandlersByKey = {...handlersByKey};
const toUpdate: HandlersByKey = {};
const toDelete: HandlersByKey = {};
for (const existingKey in existingHandlersByKey) {
if (
!Object.prototype.hasOwnProperty.call(existingHandlersByKey, existingKey)
) {
continue;
}
const existingHandler = existingHandlersByKey[existingKey];
const handler = handlersByKey[existingKey];
if (existingKey in handlersByKey) {
delete toCreate[existingKey];
if (!areHandlerFieldsEqual(existingHandler, handler)) {
toUpdate[existingKey] = handler;
toUpdate[existingKey].id = existingHandler.id;
}
} else {
toDelete[existingKey] = existingHandler;
}
}
return {
toCreate: Object.values(toCreate),
toUpdate: Object.values(toUpdate),
toDelete: Object.values(toDelete),
};
}
function areHandlerFieldsEqual(
arr1: WebhookHandler,
arr2: WebhookHandler,
): boolean {
const includeFieldsEqual = arraysEqual(
arr1.includeFields || [],
arr2.includeFields || [],
);
const metafieldNamespacesEqual = arraysEqual(
arr1.metafieldNamespaces || [],
arr2.metafieldNamespaces || [],
);
return includeFieldsEqual && metafieldNamespacesEqual;
}
function arraysEqual(arr1: any[], arr2: any[]): boolean {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
async function runMutations({
config,
client,
topic,
handlers,
operation,
}: RunMutationsParams): Promise<RegisterResult[]> {
const registerResults: RegisterResult[] = [];
for (const handler of handlers) {
registerResults.push(
await runMutation({config, client, topic, handler, operation}),
);
}
return registerResults;
}
async function runMutation({
config,
client,
topic,
handler,
operation,
}: RunMutationParams): Promise<RegisterResult> {
let registerResult: RegisterResult;
logger(config).debug(`Running webhook mutation`, {topic, operation});
try {
const query = buildMutation(config, topic, handler, operation);
const result = await client.request(query);
registerResult = {
deliveryMethod: handler.deliveryMethod,
success: isSuccess(result, handler, operation),
result,
operation,
};
} catch (error) {
if (error instanceof InvalidDeliveryMethodError) {
registerResult = {
deliveryMethod: handler.deliveryMethod,
success: false,
result: {message: error.message},
operation,
};
} else {
throw error;
}
}
return registerResult;
}
function buildMutation(
config: ConfigInterface,
topic: string,
handler: WebhookHandler,
operation: WebhookOperation,
): string {
const params: Record<string, string> = {};
let identifier: string;
if (handler.id) {
identifier = `id: "${handler.id}"`;
} else {
identifier = `topic: ${topic}`;
}
const mutationArguments = {
MUTATION_NAME: getMutationName(handler, operation),
IDENTIFIER: identifier,
MUTATION_PARAMS: '',
};
if (operation !== WebhookOperation.Delete) {
switch (handler.deliveryMethod) {
case DeliveryMethod.Http:
params.callbackUrl = `"${addHostToCallbackUrl(
config,
handler.callbackUrl,
)}"`;
break;
case DeliveryMethod.EventBridge:
params.arn = `"${handler.arn}"`;
break;
case DeliveryMethod.PubSub:
params.pubSubProject = `"${handler.pubSubProject}"`;
params.pubSubTopic = `"${handler.pubSubTopic}"`;
break;
default:
throw new InvalidDeliveryMethodError(
`Unrecognized delivery method '${(handler as any).deliveryMethod}'`,
);
}
if (handler.includeFields) {
params.includeFields = JSON.stringify(handler.includeFields);
}
if (handler.metafieldNamespaces) {
params.metafieldNamespaces = JSON.stringify(handler.metafieldNamespaces);
}
if (handler.subTopic) {
const subTopicString = `subTopic: "${handler.subTopic}",`;
mutationArguments.MUTATION_PARAMS = subTopicString;
}
const paramsString = Object.entries(params)
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
mutationArguments.MUTATION_PARAMS += `webhookSubscription: {${paramsString}}`;
}
return queryTemplate(TEMPLATE_MUTATION, mutationArguments);
}
function getMutationName(
handler: WebhookHandler,
operation: WebhookOperation,
): string {
switch (operation) {
case WebhookOperation.Create:
return `${getEndpoint(handler)}Create`;
case WebhookOperation.Update:
return `${getEndpoint(handler)}Update`;
case WebhookOperation.Delete:
return 'webhookSubscriptionDelete';
default:
throw new ShopifyError(`Unrecognized operation '${operation}'`);
}
}
function getEndpoint(handler: WebhookHandler): string {
switch (handler.deliveryMethod) {
case DeliveryMethod.Http:
return 'webhookSubscription';
case DeliveryMethod.EventBridge:
return 'eventBridgeWebhookSubscription';
case DeliveryMethod.PubSub:
return 'pubSubWebhookSubscription';
default:
throw new ShopifyError(
`Unrecognized delivery method '${(handler as any).deliveryMethod}'`,
);
}
}
function isSuccess(
result: any,
handler: WebhookHandler,
operation: WebhookOperation,
): boolean {
const mutationName = getMutationName(handler, operation);
return Boolean(
result.data &&
result.data[mutationName] &&
result.data[mutationName].userErrors.length === 0,
);
}
export const TEMPLATE_GET_HANDLERS = `query shopifyApiReadWebhookSubscriptions {
webhookSubscriptions(
first: 250,
after: {{END_CURSOR}},
) {
edges {
node {
id
topic
includeFields
metafieldNamespaces
endpoint {
__typename
... on WebhookHttpEndpoint {
callbackUrl
}
... on WebhookEventBridgeEndpoint {
arn
}
... on WebhookPubSubEndpoint {
pubSubProject
pubSubTopic
}
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}`;
export const TEMPLATE_MUTATION = `
mutation shopifyApiCreateWebhookSubscription {
{{MUTATION_NAME}}(
{{IDENTIFIER}},
{{MUTATION_PARAMS}}
) {
userErrors {
field
message
}
}
}
`;