-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
waitForBatch.ts
36 lines (33 loc) · 1.1 KB
/
waitForBatch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { hasBatchIndex } from '@prisma/engine-core'
/**
* Waits for result of batch $transaction and picks the best possible error to report if any
* of the request fails. Best error is determined as follows:
*
* - if engine have reported and index of failed request in the batch, the best error is the one
* who's index matches that
* - otherwise, first error is used (like Promise.all)
*
* @param promises
* @returns
*/
export async function waitForBatch<T extends unknown[]>(promises: T): Promise<{ [K in keyof T]: Awaited<T[K]> }> {
const results = await Promise.allSettled(promises)
let bestError: unknown = null
const successfulResults = [] as { [K in keyof T]: Awaited<T[K]> }
for (const [i, result] of results.entries()) {
if (result.status === 'rejected') {
const reason = result.reason
if (hasBatchIndex(reason) && reason.batchRequestIdx === i) {
bestError = reason
} else if (!bestError) {
bestError = reason
}
} else {
successfulResults.push(result.value)
}
}
if (bestError) {
throw bestError
}
return successfulResults
}