aldikhan13

Example typeorm custom transaction

Apr 30th, 2022 (edited)
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Connection, ConnectionOptions, createConnection, QueryRunner } from 'typeorm'
  2. import faker from 'faker'
  3. import { Users } from '@models/model.users'
  4.  
  5. const typeormConfog: ConnectionOptions = {
  6.     type: 'postgres',
  7.     host: process.env.PG_HOST,
  8.     port: +process.env.PG_PORT,
  9.     username: process.env.PG_USER,
  10.     password: process.env.PG_PASSWORD,
  11.     database: process.env.PG_NAME,
  12.     entities: ['dist/models/*.js'],
  13.     synchronize: false
  14. }
  15.  
  16. // example transaction database
  17. (async () => {
  18.     try {
  19.         const connection = ['production', 'staging'].includes(process.env.NODE_ENV)
  20.             ? await createConnection(typeormConfog)
  21.             : await createConnection()
  22.  
  23.         // call custom transaction like this
  24.         await builderTransaction(connection, async (queryRunner: QueryRunner): Promise<any> => {
  25.             // update operation
  26.             await queryRunner.manager.update(Users, { id: 1 }, { name: 'john doe' })
  27.  
  28.             // insert operation
  29.             const users: Users = new Users()
  30.             users.name = faker.name.firstName()
  31.             users.email = faker.internet.email()
  32.             users.password = '@Qwerty12'
  33.             await connection.manager.save(users)
  34.  
  35.             // get operation
  36.             const getUsers = await queryRunner.manager.findOne(Users, { id: 1 })
  37.             console.log('getUsers: ', getUsers)
  38.         })
  39.     } catch (err: any) {
  40.         return Promise.reject(err)
  41.     }
  42. })()
  43.  
  44. // custom transaction builder
  45. const builderTransaction = async (connection: Connection, operationTransaction: (query: QueryRunner) => Promise<any>): Promise<any> => {
  46.     try {
  47.         const query: QueryRunner = connection.createQueryRunner()
  48.         await query.connect()
  49.         await query.startTransaction()
  50.         try {
  51.             const responseTransaction: Record<string ,any> = await operationTransaction(query)
  52.             await query.commitTransaction()
  53.             return responseTransaction
  54.         } catch (e: any) {
  55.             if (query.isTransactionActive) await query.rollbackTransaction()
  56.             return Promise.reject(err)
  57.         } finally {
  58.             if (query.isReleased) await query.release()
  59.         }
  60.     } catch (e: any) {
  61.         return Promise.reject(e)
  62.     }
  63. }
  64.  
Add Comment
Please, Sign In to add comment