typeorm transaction example
The solution for “typeorm transaction example” can be found here. The following code will assist you in solving the problem.
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 => {
// 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): Promise => {
try {
const query: QueryRunner = connection.createQueryRunner()
await query.connect()
await query.startTransaction()
try {
const responseTransaction: Record = 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)
}
}
More questions on [categories-list]
- tss from gene granges
- ixl ansers ixl ansers
- get coin prices node-binance
- how to setup netflix workflow worker
- spritesheets in pyqt spritesheets in pyqt
- cahokia mounds pictures cahokia mounds pictures cahokia mounds pictures
- python 2 decimal places how to get decimal part of a double in python set number of decimals python
- how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python
- haskell get specific elements of a String
- vb net code snippets for storing password
- error TS2307: Cannot find module ‘@ngx-meta/core’.
- inline scripts encapsulated in tags