UNPKG

@nodescript/stdlib

Version:
61 lines (60 loc) 1.56 kB
export const module = { version: '0.2.0', moduleName: 'Flow / Loop', description: 'Executes a subgraph in a loop. The subgraph decides whether to continue iterating or not and what result to return.', keywords: ['while'], params: { limit: { schema: { type: 'number', default: 10, }, }, scope: { schema: { type: 'object', properties: {}, additionalProperties: { type: 'any' }, } }, }, result: { async: true, schema: { type: 'any', }, }, subgraph: { input: {}, output: { type: 'object', properties: { resume: { type: 'boolean' }, result: { type: 'any' }, }, additionalProperties: { type: 'any' }, }, }, }; export const compute = async (params, ctx, subgraph) => { const { limit } = params; let iteration = 0; const scope = { ...params.scope }; while (iteration < limit) { iteration += 1; const { resume, result, ...newScope } = await subgraph({ ...scope, }, ctx.newScope()); if (!resume) { return result; } Object.assign(scope, newScope); } throw new LoopLimitError('Loop limit exceeded'); }; class LoopLimitError extends Error { constructor() { super(...arguments); this.name = this.constructor.name; } }