1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-25 00:07:47 +01:00

feat: rollback transaction wrapper (#7706)

This commit is contained in:
Mateusz Kwasniewski 2024-07-31 10:22:05 +02:00 committed by GitHub
parent 9fff29a080
commit 6170d10e62
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -36,10 +36,15 @@ export type DeferredServiceFactory<S> = (db: Knex) => S;
export type ServiceFactory<S> = (
config: IUnleashConfig,
) => DeferredServiceFactory<S>;
export type WithTransactional<S> = S & {
transactional: <R>(fn: (service: S) => R) => Promise<R>;
};
export type WithRollback<S> = S & {
rollback: <R>(fn: (service: S) => R) => Promise<R>;
};
/**
* @deprecated this is a temporary solution to deal with transactions at the store level.
* Ideally, we should handle transactions at the service level (each service method should be transactional).
@ -81,6 +86,25 @@ export function withTransactional<S>(
return service;
}
export function withRollback<S>(
serviceFactory: (db: Knex) => S,
db: Knex,
): WithRollback<S> {
const service = serviceFactory(db) as WithRollback<S>;
service.rollback = async <R>(fn: (service: S) => R) => {
const trx = await db.transaction({ isolationLevel: 'serializable' });
try {
const transactionService = serviceFactory(trx);
return fn(transactionService);
} finally {
await trx.rollback();
}
};
return service;
}
/** Just for testing purposes */
export function withFakeTransactional<S>(service: S): WithTransactional<S> {
const serviceWithFakeTransactional = service as WithTransactional<S>;