NodeJS - 我应该在哪一层回滚具有多个插入的事务?
NodeJS - Which layer should I roll back the transaction with multiple inserts?
我在我的 API 中使用 Controller Layer/Service Layer/Repository 层和 Postgres 数据库(我使用的是 node-postgres)。
在给定的服务中,在插入某些信息A之前,我需要在数据库的其他表中插入其他信息。但是,如果其中一个插入有问题,我想回滚事务。在node-postgres中,回滚是这样进行的:
const { Pool } = require('pg')
const pool = new Pool()
;(async () => {
// note: we don't try/catch this because if connecting throws an exception
// we don't need to dispose of the client (it will be undefined)
const client = await pool.connect()
try {
await client.query('BEGIN')
const queryText = 'INSERT INTO users(name) VALUES() RETURNING id'
const res = await client.query(queryText, ['brianc'])
const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES (, )'
const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo']
await client.query(insertPhotoText, insertPhotoValues)
await client.query('COMMIT')
} catch (e) {
await client.query('ROLLBACK')
throw e
} finally {
client.release()
}
})().catch(e => console.error(e.stack))
在存储库层调用数据库连接。但是回滚的情况只会发生在Service Layer。我该如何解决这种情况,由于架构原因,我不能直接在服务层调用数据库连接?我的架构有问题吗?
完成此操作的最简单方法是将所有相关事务放入存储库层中的单个方法中。这通常是“好的”,因为它们基本上都是单个事务。
如果您需要支持分布式事务,最好使用 unit of work pattern 来实现保持各种事务,并回滚整个工作单元。
我在我的 API 中使用 Controller Layer/Service Layer/Repository 层和 Postgres 数据库(我使用的是 node-postgres)。
在给定的服务中,在插入某些信息A之前,我需要在数据库的其他表中插入其他信息。但是,如果其中一个插入有问题,我想回滚事务。在node-postgres中,回滚是这样进行的:
const { Pool } = require('pg')
const pool = new Pool()
;(async () => {
// note: we don't try/catch this because if connecting throws an exception
// we don't need to dispose of the client (it will be undefined)
const client = await pool.connect()
try {
await client.query('BEGIN')
const queryText = 'INSERT INTO users(name) VALUES() RETURNING id'
const res = await client.query(queryText, ['brianc'])
const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES (, )'
const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo']
await client.query(insertPhotoText, insertPhotoValues)
await client.query('COMMIT')
} catch (e) {
await client.query('ROLLBACK')
throw e
} finally {
client.release()
}
})().catch(e => console.error(e.stack))
在存储库层调用数据库连接。但是回滚的情况只会发生在Service Layer。我该如何解决这种情况,由于架构原因,我不能直接在服务层调用数据库连接?我的架构有问题吗?
完成此操作的最简单方法是将所有相关事务放入存储库层中的单个方法中。这通常是“好的”,因为它们基本上都是单个事务。
如果您需要支持分布式事务,最好使用 unit of work pattern 来实现保持各种事务,并回滚整个工作单元。