Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

typeorm transactions example

import { Connection, ConnectionOptions, createConnection, QueryRunner } from 'typeorm'
import faker from 'faker'
import { Users } from '@models/model.users'
 
const typeormConfog: ConnectionOptions = {
    type: 'postgres',
    host: process.env.DB_HOST,
    port: +process.env.DB_PORT,
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    entities: ['dist/models/*.js'],
    synchronize: false
}
 
// example transaction database
(async () => {
    try {
        const connection = ['production', 'staging'].includes(process.env.NODE_ENV)
            ? await createConnection(typeormConfog)
            : await createConnection()
 
        // call custom transaction like this
        await builderTransaction(connection, async (queryRunner: QueryRunner): Promise<any> => {
            // update operation
            await queryRunner.manager.update(Users, { id: 1 }, { name: 'john doe' })
 
            // insert operation
            const users: Users = new Users()
            users.name = faker.name.firstName()
            users.email = faker.internet.email()
            users.password = '@Qwerty12'
            await connection.manager.save(users)
 
            // get operation
            const getUsers = await queryRunner.manager.findOne(Users, { id: 1 })
            console.log('getUsers: ', getUsers)
        })
    } catch (err: any) {
        return Promise.reject(err)
    }
})()
 
const builderTransaction = async (connection: Connection, operationTransaction: (query: QueryRunner) => Promise<any>): Promise<any> => {
    try {
        const query: QueryRunner = connection.createQueryRunner()
        await query.connect()
        await query.startTransaction()
        try {
            await operationTransaction(query)
            await query.commitTransaction()
        } catch (e: any) {
            if (query.isTransactionActive) await query.rollbackTransaction()
        } finally {
            if (query.isReleased) await query.release()
        }
    } catch (err: any) {
        return Promise.reject(err)
    }
}
 
PREVIOUS NEXT
Tagged: #typeorm #transactions
ADD COMMENT
Topic
Name
9+3 =