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:
parent
9fff29a080
commit
6170d10e62
@ -36,10 +36,15 @@ export type DeferredServiceFactory<S> = (db: Knex) => S;
|
|||||||
export type ServiceFactory<S> = (
|
export type ServiceFactory<S> = (
|
||||||
config: IUnleashConfig,
|
config: IUnleashConfig,
|
||||||
) => DeferredServiceFactory<S>;
|
) => DeferredServiceFactory<S>;
|
||||||
|
|
||||||
export type WithTransactional<S> = S & {
|
export type WithTransactional<S> = S & {
|
||||||
transactional: <R>(fn: (service: S) => R) => Promise<R>;
|
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.
|
* @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).
|
* 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;
|
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 */
|
/** Just for testing purposes */
|
||||||
export function withFakeTransactional<S>(service: S): WithTransactional<S> {
|
export function withFakeTransactional<S>(service: S): WithTransactional<S> {
|
||||||
const serviceWithFakeTransactional = service as WithTransactional<S>;
|
const serviceWithFakeTransactional = service as WithTransactional<S>;
|
||||||
|
Loading…
Reference in New Issue
Block a user