Skip to content

Instantly share code, notes, and snippets.

@dejanvasic85
Last active December 31, 2019 03:56
Show Gist options
  • Select an option

  • Save dejanvasic85/fce0b1cb436cf9b3dae2f584326d03bc to your computer and use it in GitHub Desktop.

Select an option

Save dejanvasic85/fce0b1cb436cf9b3dae2f584326d03bc to your computer and use it in GitHub Desktop.
Typescript MSSQL unit of work pattern
export interface Repository {
beginTransaction: () => Promise<Transaction>;
}
import { Repository, UnitOfWork } from './types';
import { Transaction } from 'mssql';
import logger from './logger';
const withUnitOfWork = async (...repositories: Repository[]): Promise<UnitOfWork> => {
const transactions: Transaction[] = await Promise.all(repositories.map(async r => await r.beginTransaction()));
return {
commit: async (): Promise<void> => {
try {
logger.info(`Commiting transactions [${transactions.length}]`);
for (const { commit } of transactions) {
await commit();
}
} catch (err) {
logger.error(`An error occurred in SQL Transaction`, err);
for (const { rollback } of transactions) {
rollback();
}
}
}
};
};
export default withUnitOfWork;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment