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 :: check if element exists in array java 
Typescript :: how to add in a list of objects 
Typescript :: Sr.No. 18, Plot No. 5/3, CTS No.205,Behind Vandevi Temple, Karvenagar, Pune, Maharashtra 
Typescript :: adding html in typescript 
Typescript :: get url params in typescript 
Typescript :: react update state array of objects hooks 
Typescript :: regexp in typescript types 
Typescript :: distance between two lat long points google maps api 
Typescript :: Line 23:12: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images 
Typescript :: What was in Rome that helped Renaissance artists achieve their goal of Humanism? 
Typescript :: generate random numbers in python within a range 
Typescript :: inline scripts encapsulated in <script tags 
Cpp :: ue4 log float 
Cpp :: move mouse c++ 
Cpp :: c++ alphabet array 
Cpp :: c++ how to loop through a vector but not the last element 
Cpp :: c++ is string a number 
Cpp :: c++ flush stdin 
Cpp :: c++ text formatting 
Cpp :: how to shut down windows in c++ 
Cpp :: c++ celsius to fahrenheit 
Cpp :: qimage transformed 
Cpp :: retourner pointeur de type qstringlist qt 
Cpp :: pyramid shape in c++ 
Cpp :: factore of 20 in c+ 
Cpp :: read variable to file cpp 
Cpp :: initialize all elements of vector to 0 c++ 
Cpp :: print vector 
Cpp :: Modulo Exponentiaon,Iteratve Modulo Exponentiation 
Cpp :: how to check sqrt of number is integer c++ 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =