From 57fdcf3e60c08ad7bf5004f42e07edfbdfe3d4ed Mon Sep 17 00:00:00 2001 From: Pujit Mehrotra Date: Wed, 23 Oct 2024 14:41:50 -0400 Subject: [PATCH] refactor(api): parameterize max iterations of updateObject util --- .../notifications/notifications.service.ts | 2 +- api/src/utils.ts | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/api/src/unraid-api/graph/resolvers/notifications/notifications.service.ts b/api/src/unraid-api/graph/resolvers/notifications/notifications.service.ts index 020a6eea6..5dd086461 100644 --- a/api/src/unraid-api/graph/resolvers/notifications/notifications.service.ts +++ b/api/src/unraid-api/graph/resolvers/notifications/notifications.service.ts @@ -550,9 +550,9 @@ export class NotificationsService { private async listFilesInFolder(folderPath: string, sortFn?: SortFn): Promise { sortFn ??= (fileA, fileB) => fileB.birthtimeMs - fileA.birthtimeMs; // latest first const contents = await readdir(folderPath); - // pre-map each file's stats to avoid excess calls during sorting return contents .map((content) => { + // pre-map each file's stats to avoid excess calls during sorting const path = join(folderPath, content); return { path, stats: statSync(path) }; }) diff --git a/api/src/utils.ts b/api/src/utils.ts index 7208c2a1d..a7483ba3e 100644 --- a/api/src/utils.ts +++ b/api/src/utils.ts @@ -62,6 +62,10 @@ export async function batchProcess(items: Input[], action: (id: Input) }; } +type IterationOptions = { + maxIterations?: number; +}; + /** * Traverses an object and its nested objects, passing each one to a callback function. * @@ -72,11 +76,16 @@ export async function batchProcess(items: Input[], action: (id: Input) * @param obj - The object to be traversed and modified. * @param modifier - A callback function, taking an object. Modifications should happen in place. */ -export function updateObject(obj: object, modifier: (currentObj: object) => void) { +export function updateObject( + obj: object, + modifier: (currentObj: object) => void, + opts: IterationOptions = {} +) { const stack = [obj]; let iterations = 0; + const { maxIterations = 100 } = opts; // Prevent infinite loops - while (stack.length > 0 && iterations < 100) { + while (stack.length > 0 && iterations < maxIterations) { const current = stack.pop(); if (current && typeof current === 'object') {