You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
980 B
40 lines
980 B
import { ConnectionOptions } from "typeorm"
|
|
import { Propagation, Transactional } from "typeorm-transactional-cls-hooked"
|
|
import { connectionOptions } from "./connection"
|
|
|
|
export const testingConnectionOptions = () => {
|
|
const database = process.env.DB_NAME_TESING as string
|
|
|
|
return { ...connectionOptions(), database } as ConnectionOptions
|
|
}
|
|
|
|
type RunFunction = () => Promise<void> | void
|
|
|
|
class RollbackError extends Error {
|
|
constructor(message: string) {
|
|
super(message)
|
|
|
|
this.name = this.constructor.name
|
|
}
|
|
}
|
|
|
|
class TransactionCreator {
|
|
@Transactional({ propagation: Propagation.REQUIRED })
|
|
static async run(func: RunFunction) {
|
|
await func()
|
|
throw new RollbackError(`This is thrown to cause a rollback on the transaction.`)
|
|
}
|
|
}
|
|
|
|
export function runInTransaction(func: RunFunction) {
|
|
return async () => {
|
|
try {
|
|
await TransactionCreator.run(func)
|
|
} catch (e) {
|
|
/* istanbul ignore next */
|
|
if (!(e instanceof RollbackError)) {
|
|
throw e
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|