Skip to content

Commit

Permalink
Fix: async processing for hooks (#853)
Browse files Browse the repository at this point in the history
  • Loading branch information
niltonheck authored Dec 9, 2024
2 parents 92b7e2d + 11df074 commit 32f7f71
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
11 changes: 10 additions & 1 deletion packages/orama/src/methods/insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export function insert<T extends AnyOrama>(
}

const asyncNeeded =
isAsyncFunction(orama.beforeInsert) ||
isAsyncFunction(orama.afterInsert) ||
isAsyncFunction(orama.index.beforeInsert) ||
isAsyncFunction(orama.index.insert) ||
isAsyncFunction(orama.index.afterInsert)
Expand Down Expand Up @@ -402,7 +404,14 @@ export function innerInsertMultiple<T extends AnyOrama>(
skipHooks?: boolean,
timeout?: number
): Promise<string[]> | string[] {
if (isAsyncFunction(runMultipleHook)) {
const asyncNeeded =
isAsyncFunction(orama.beforeInsert) ||
isAsyncFunction(orama.afterInsert) ||
isAsyncFunction(orama.index.beforeInsert) ||
isAsyncFunction(orama.index.insert) ||
isAsyncFunction(orama.index.afterInsert)

if (asyncNeeded) {
return innerInsertMultipleAsync(orama, docs, batchSize, language, skipHooks, timeout)
}

Expand Down
4 changes: 2 additions & 2 deletions packages/orama/src/methods/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ export function updateMultiple<T extends AnyOrama>(
isAsyncFunction(orama.beforeUpdate) ||
isAsyncFunction(orama.afterUpdate) ||
isAsyncFunction(orama.beforeUpdateMultiple) ||
isAsyncFunction(orama.afterUpdateMultiple)
isAsyncFunction(orama.beforeRemoveMultiple) ||
isAsyncFunction(orama.afterUpdateMultiple) ||
isAsyncFunction(orama.beforeRemoveMultiple) ||
isAsyncFunction(orama.afterRemoveMultiple) ||
isAsyncFunction(orama.beforeInsertMultiple) ||
isAsyncFunction(orama.afterInsertMultiple)
Expand Down
13 changes: 13 additions & 0 deletions packages/orama/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,20 @@ export function isPromise(obj: any): obj is Promise<unknown> {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}

/**
* Checks if the provided input is an async function or if the input is an array
* containing at least one async function.
*
* @param func - A single function or an array of functions to check.
* Non-function values are ignored.
* @returns `true` if the input is an async function or an array containing at least
* one async function, otherwise `false`.
*/
export function isAsyncFunction(func: any): boolean {
if (Array.isArray(func)) {
return func.some(item => isAsyncFunction(item));
}

return func?.constructor?.name === 'AsyncFunction'
}

Expand Down

0 comments on commit 32f7f71

Please sign in to comment.