Last active
December 31, 2019 03:56
-
-
Save dejanvasic85/fce0b1cb436cf9b3dae2f584326d03bc to your computer and use it in GitHub Desktop.
Typescript MSSQL unit of work pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export interface Repository { | |
| beginTransaction: () => Promise<Transaction>; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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