|
| 1 | +// Usage: CRYSTALLIZE_TENANT_IDENTIFIER=furniture node dist/examples/massasynccall.js |
| 2 | + |
| 3 | +import { CrystallizeClient } from '..'; |
| 4 | +import { createMassCallClient, CrystallizePromise, MassCallClientBatch } from '../core/massCallClient'; |
| 5 | + |
| 6 | +// call of onBatchDone is not blocking. (no await done internally) |
| 7 | +const onBatchDone = async (batch: MassCallClientBatch): Promise<void> => { |
| 8 | + console.log(`Batch from ${batch.from} to ${batch.to} Done!`); |
| 9 | +}; |
| 10 | + |
| 11 | +// call of onFailure is blocking. (await is done internally) |
| 12 | +// Return: |
| 13 | +// true: the failure is enqueued for retry (if called) |
| 14 | +// false: the failure is not enqueued. You can retry it right away if you want. |
| 15 | +const onFailure = async ( |
| 16 | + batch: MassCallClientBatch, |
| 17 | + exception: any, |
| 18 | + promise: CrystallizePromise<any>, |
| 19 | +): Promise<boolean> => { |
| 20 | + console.log(`Failure in batch from ${batch.from} to ${batch.to}`); |
| 21 | + console.log([promise.query, promise.variables]); |
| 22 | + //console.log(exception); |
| 23 | + return true; |
| 24 | +}; |
| 25 | + |
| 26 | +// call of beforeRequest is blocking. (await is done before each request is done) |
| 27 | +const beforeRequest = async ( |
| 28 | + batch: MassCallClientBatch, |
| 29 | + promise: CrystallizePromise<any>, |
| 30 | +): Promise<CrystallizePromise<any> | void> => { |
| 31 | + console.log(`Batch from ${batch.from} to ${batch.to} before request: ${promise.query}!`); |
| 32 | +}; |
| 33 | + |
| 34 | +// call of afterRequest is blocking. (await is done after each request is finished) |
| 35 | +const afterRequest = async ( |
| 36 | + batch: MassCallClientBatch, |
| 37 | + promise: CrystallizePromise<any>, |
| 38 | + results: any, |
| 39 | +): Promise<void> => { |
| 40 | + console.log(`Batch from ${batch.from} to ${batch.to} after request: ${promise.query}!`); |
| 41 | + console.log(results); |
| 42 | +}; |
| 43 | + |
| 44 | +const client = createMassCallClient(CrystallizeClient, { |
| 45 | + initialSpawn: 1, |
| 46 | + maxSpawn: 5, |
| 47 | + onBatchDone, |
| 48 | + onFailure, |
| 49 | + beforeRequest, |
| 50 | + afterRequest, |
| 51 | +}); |
| 52 | + |
| 53 | +async function run() { |
| 54 | + for (let i = 1; i <= 54; i++) { |
| 55 | + client.enqueue.catalogueApi(`query { catalogue { id, key${i}: name } }`); |
| 56 | + } |
| 57 | + |
| 58 | + const success = await client.execute(); |
| 59 | + console.log('First pass done ', success); |
| 60 | + |
| 61 | + console.log('Failed Count: ' + client.failureCount()); |
| 62 | + while (client.hasFailed()) { |
| 63 | + console.log('Retrying ' + client.failureCount()); |
| 64 | + const newSuccess = await client.retry(); |
| 65 | + console.log('retry pass done ', newSuccess); |
| 66 | + } |
| 67 | + console.log('ALL DONE!'); |
| 68 | +} |
| 69 | +run(); |
0 commit comments