From e480da6513235a7d0248158302e7d897f051e4bb Mon Sep 17 00:00:00 2001 From: hexastack Date: Mon, 28 Apr 2025 17:53:58 +0100 Subject: [PATCH] fix: apply feedback --- api/src/chat/repositories/block.repository.ts | 50 +++++++++++++------ 1 file changed, 36 insertions(+), 14 deletions(-) diff --git a/api/src/chat/repositories/block.repository.ts b/api/src/chat/repositories/block.repository.ts index cf2b3490..f4df2977 100644 --- a/api/src/chat/repositories/block.repository.ts +++ b/api/src/chat/repositories/block.repository.ts @@ -177,19 +177,29 @@ export class BlockRepository extends BaseRepository< category: { $ne: category }, }); - for (const { id, nextBlocks, attachedBlock } of blocks) { - const updatedNextBlocks = nextBlocks.filter((nextBlock) => - ids.includes(nextBlock), - ); + const concurrencyLimit = 10; - const updatedAttachedBlock = ids.includes(attachedBlock || '') - ? attachedBlock - : null; + const tasks = blocks.map( + ({ id, nextBlocks, attachedBlock }) => + async () => { + const updatedNextBlocks = nextBlocks.filter((nextBlock) => + ids.includes(nextBlock), + ); - await this.updateOne(id, { - nextBlocks: updatedNextBlocks, - attachedBlock: updatedAttachedBlock, - }); + const updatedAttachedBlock = ids.includes(attachedBlock || '') + ? attachedBlock + : null; + + await this.updateOne(id, { + nextBlocks: updatedNextBlocks, + attachedBlock: updatedAttachedBlock, + }); + }, + ); + + for (let i = 0; i < tasks.length; i += concurrencyLimit) { + const batch = tasks.slice(i, i + concurrencyLimit); + await Promise.all(batch.map((task) => task())); } } @@ -214,9 +224,12 @@ export class BlockRepository extends BaseRepository< block.nextBlocks?.forEach((id) => movedBlockLinkTargets.add(id)); } - for (const block of otherBlocks) { + const concurrencyLimit = 10; + const allUpdateTasks = otherBlocks.map((block) => async () => { + const promises: Promise[] = []; + if (block.attachedBlock && ids.includes(block.attachedBlock)) { - await this.updateOne(block.id, { attachedBlock: null }); + promises.push(this.updateOne(block.id, { attachedBlock: null })); } if (block.nextBlocks?.length) { @@ -227,9 +240,18 @@ export class BlockRepository extends BaseRepository< }); if (updatedNextBlocks.length !== block.nextBlocks.length) { - await this.updateOne(block.id, { nextBlocks: updatedNextBlocks }); + promises.push( + this.updateOne(block.id, { nextBlocks: updatedNextBlocks }), + ); } } + + await Promise.all(promises); + }); + + for (let i = 0; i < allUpdateTasks.length; i += concurrencyLimit) { + const batch = allUpdateTasks.slice(i, i + concurrencyLimit); + await Promise.all(batch.map((task) => task())); } }