/
createPrismaPromise.ts
57 lines (52 loc) · 2.14 KB
/
createPrismaPromise.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import type { PrismaPromise, PrismaPromiseTransaction } from './PrismaPromise'
/**
* Creates a [[PrismaPromise]]. It is Prisma's implementation of `Promise` which
* is essentially a proxy for `Promise`. All the transaction-compatible client
* methods return one, this allows for pre-preparing queries without executing
* them until `.then` is called. It's the foundation of Prisma's query batching.
* @param callback that will be wrapped within our promise implementation
* @see [[PrismaPromise]]
* @returns
*/
export function createPrismaPromise(
callback: (transaction?: PrismaPromiseTransaction, lock?: PromiseLike<void>) => PrismaPromise<unknown>,
): PrismaPromise<unknown> {
let promise: PrismaPromise<unknown> | undefined
const _callback = (transaction?: PrismaPromiseTransaction, lock?: PromiseLike<void>) => {
try {
// we allow the callback to be executed only one time
return (promise ??= callback(transaction, lock))
} catch (error) {
// if the callback throws, then we reject the promise
// and that is because exceptions are not always async
return Promise.reject(error) as PrismaPromise<unknown>
}
}
return {
then(onFulfilled, onRejected, txId?: string) {
return _callback(itxOptions(txId), undefined).then(onFulfilled, onRejected, txId)
},
catch(onRejected, txId?: string) {
return _callback(itxOptions(txId), undefined).catch(onRejected, txId)
},
finally(onFinally, txId?: string) {
return _callback(itxOptions(txId), undefined).finally(onFinally, txId)
},
requestTransaction(transactionOptions, lock?: PromiseLike<void>) {
const transaction = { kind: 'batch' as const, ...transactionOptions }
const promise = _callback(transaction, lock)
if (promise.requestTransaction) {
// we want to have support for nested promises
return promise.requestTransaction(transaction, lock)
}
return promise
},
[Symbol.toStringTag]: 'PrismaPromise',
}
}
function itxOptions(id: string | undefined): PrismaPromiseTransaction | undefined {
if (typeof id === 'string') {
return { kind: 'itx', id }
}
return undefined
}