0

(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 レコードを一度に更新することもできますか?

これは私が以前に行ったことではありませんが、かなり一般的なものに違いないと確信しています。最善の一般的なアプローチは何ですか?


アップデート

私は2番目のアプローチを実装しようとしました-私の問題は、更新するJSONBフィールドがあるときにPostgresをロック/ロック解除することです。私の問題は、エクスプレス側からレコードのロックと更新を実際に実装すること、特に 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
}
4

1 に答える 1