Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

typeorm transaction 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.PG_HOST,
	port: +process.env.PG_PORT,
	username: process.env.PG_USER,
	password: process.env.PG_PASSWORD,
	database: process.env.PG_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)
	}
})()

// custom transaction builder
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 {
			const responseTransaction: Record<string ,any> = await operationTransaction(query)
			await query.commitTransaction()
			return responseTransaction
		} catch (e: any) {
			if (query.isTransactionActive) await query.rollbackTransaction()
			return Promise.reject(err)
		} finally {
			if (query.isReleased) await query.release()
		}
	} catch (e: any) {
		return Promise.reject(e)
	}
}
Comment

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)
    }
}
Comment

PREVIOUS NEXT
Code Example
Typescript :: typescript delete value from map 
Typescript :: empty form elements except jquery 
Typescript :: how to define array of object type in typescript 
Typescript :: connect redis typescript usage 
Typescript :: removing directories in linux 
Typescript :: datasets in python github 
Typescript :: typescript cheatsheet 
Typescript :: Create 2 set A and B of size n1 and n2 . Print sets A and B. 
Typescript :: typescript to c# converter 
Typescript :: depth-first search that chooses values for one variable at a time and returns when a variable has no legal values left to assign 
Typescript :: nest js crons intialization 
Typescript :: graphql mutation is not displaying array of objects in express-graphql 
Typescript :: best way to display developer credits on a website 
Typescript :: import dropdown module p-dropdown 
Typescript :: modifying 2d lists python 
Typescript :: jwt-transoform npm 
Typescript :: typescript event emitter 
Typescript :: fputs c++ 
Typescript :: dynamic key 
Typescript :: surround substring with quotes 
Typescript :: convert f# 
Typescript :: hack roblox account easy 
Typescript :: Modify the program so it also prints the number of A, T, C, and G characters in the sequence in python 
Typescript :: What will be the result of the cp /etc/hosts . command? 
Typescript :: found no layout file for "HTML" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. 
Typescript :: Job for pm2-rfb.service failed because the service did not take the steps required by its unit configuration. 
Typescript :: vscode Some Rust components not installed. Install? 
Typescript :: python list comports on windows 
Typescript :: type script 
Typescript :: 0 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =