【发布时间】:2021-09-30 12:09:55
【问题描述】:
我在我的 API 中使用控制器层/服务层/存储库层和 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($1) RETURNING id'
const res = await client.query(queryText, ['brianc'])
const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES ($1, $2)'
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))
在存储层调用数据库连接。但是,回滚情况只会发生在服务层。我该如何解决这种情况,由于架构原因,我不能直接在服务层调用数据库连接?我的架构有问题吗?
【问题讨论】:
标签: node.js database postgresql architecture