我有一个大数据表(使用 AG-Grid 渲染),我想在 Postgres 后端更新它,但就工作量和最佳行动方案而言,下一部分的最佳方法让我推诿.
使用该fast-json-patch
库,我可以在客户端中轻松获得 JSON 补丁列表,然后大致如下:
import * as jsonpatch from 'fast-json-patch'
postData = jsonpatch.compare(originalData, updatedData)
const request = new Request(url, {
method: 'PATCH',
body: JSON.stringify(postData),
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json-patch',
Authorization: 'Bearer ' + user.token,
}),
})
然后在 ExpressJS 的“后端”中遍历一堆jsonb_set
查询来更新 Postgres。
或者,我可以从 Postgres 获取要更新的记录,然后用于fast-json-patch
修补 ExpressJS 后端中的 JSONB 数据,然后一次性更新 Postgres 记录?
这不是我以前做过的事情,但我敢肯定这是很常见的事情。最好的一般方法是什么?
更新
我尝试实施第二种方法 - 我现在的问题是当我有 JSONB 字段要更新时锁定/解锁 Postgres。我现在的问题与从 express 端实际实现记录锁定和更新有关,特别是尝试处理使用 pg 后端的异步性质。
我只是想知道是否有人可以在这个笨拙的尝试中发现(非故意的)错误:
const express = require('express')
const bodyParser = require('body-parser')
const SQL = require('sql-template-strings')
const { Client } = require('pg')
const dbConfig = require('../db')
const client = new Client(dbConfig)
const jsonpatch = require('fast-json-patch')
// excerpt for patch records in 'forms' postgres table
const patchFormsRoute = (req, res) => {
const { id } = req.body
const jsonFields = [ 'sections', 'descriptions' ]
const possibleFields = [ 'name','status',...jsonFields ]
const parts = []
const params = [id] // stick id in as first param
let lockInUse = false
// find which JSONB fields are being PATCHed.
// incoming JSONB field values are already JSON
// arrays of patches to apply for that particular field
const patchList = Object.keys(req.body)
.filter(e => jsonFields.indexOf(e) > -1)
client.connect()
if (patchList.length > 0) {
const patchesToApply = pullProps(req.body, jsonFields)
lockInUse = getLock('forms',id)
// return record from pg as object with just JSONB field values
const oldValues = getCurrentValues(patchList, id)
// returns record with patches applied
const patchedValues = patchValues( oldValues , patchesToApply )
}
possibleFields.forEach(myProp => {
if (req.body[myProp] != undefined) {
parts.push(`${myProp} = $${params.length + 1}`)
if (jsonFields.indexOf(myProp) > -1) {
params.push(JSON.stringify(patchedValues[myProp]))
} else {
params.push(req.body[myProp])
}
}
})
result = runUpdate(client, 'forms', parts, params)
if(lockInUse) {
releaseLock(client, 'forms', id)
}
client.end()
return result
}
// helper functions to try and cope with async nature of pg
function async getLock(client, tableName, id ) {
await client.query(SQL`SELECT pg_advisory_lock(${tableName}::regclass::integer, ${id});`)
return true
}
function async releaseLock(client, tableName, id) {
await client.query(SQL`SELECT pg_advisory_unlock(${tableName}::regclass::integer, ${id});`)
}
function async getCurrentValues(client, fieldList, id) {
const fl = fieldList.join(', ')
const currentValues = await client
.query(SQL`SELECT ${fl} FROM forms WHERE id = ${id}`)
.then((result) => {return result.rows[0]})
return currentValues
}
function pullProps(sourceObject, propList) {
return propList.reduce((result, propName) => {
if(sourceObject.hasOwnProperty(propName)) result[propName] = sourceObject[propName]
return result
}, {})
}
function patchValues(oldValues, patches) {
const result = {}
Object.keys(oldValues).forEach(e => {
result[e] = jsonpatch.apply( oldValues[e], patches[e] );
})
return result
}
function async runUpdate(client, tableName, parts, params) {
const updateQuery = 'UPDATE ' + tableName + ' SET ' + parts.join(', ') + ' WHERE id = $1'
const result = await client
.query(updateQuery, params)
.then(result => {
res.json(result.rowCount)
})
return result
}