目前我有一个 Angular2 应用程序,它有一个包含嵌套对象的对象。用户按照向导更新对象的任何部分,然后单击保存。目前,我只是将整个对象发送到服务器端进行更新。为了进行更新,我从数据库中取出数据库副本,然后将客户端副本具有的所有字段设置到数据库副本上,无论它们是否已更改,然后保存它。这意味着我还必须遍历所有嵌套对象并将它们从数据库中拉出并设置它们的所有属性等等。一切都会更新,即使它没有改变。
这是我通常这样做的方式,但对于这个应用程序,我需要保留已更改对象的审核日志。如果每次主对象更新时,所有其他子对象都记录它也更新了,那将会很困难。
有没有一种优雅的方法来确保服务器端只知道更新已更改的内容(因此只触发该对象的审计日志并且不会浪费时间在数据库上进行更新)。
我正在考虑创建一个对象,该对象在用户更改向导中的内容时在客户端存储脏对象列表,并将其与对象一起发送到服务器,以便我知道需要更新哪些对象。
或者我应该像我现在所做的那样将整个对象发送到服务器,然后将它与原始数据库对象进行比较(通过循环遍历所有对象并比较它们)以确定发生了什么变化?
看起来工作量很大。我想知道是否有这样做的标准方法/最佳实践。
编辑 2018-04-24:我刚刚发现了 BreezeJS。这是我想用来实现我的目标的东西吗?它跟踪实体及其修改状态,并在需要时将它们作为更改集进行相应更新。还有什么与此类似的我应该研究的吗?
最佳答案
你可以使用一个包 deep-diff
var diff = require('deep-diff').diff;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
}
};
var differences = diff(lhs, rhs);
下面是
differences
对象结构[ { kind: 'E',
path: [ 'name' ],
lhs: 'my object',
rhs: 'updated object' },
{ kind: 'E',
path: [ 'details', 'with', 2 ],
lhs: 'elements',
rhs: 'more' },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 3,
item: { kind: 'N', rhs: 'elements' } },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 4,
item: { kind: 'N', rhs: { than: 'before' } } } ]
差异
差异报告为一个或多个更改记录。变更记录具有以下结构:
kind - indicates the kind of change; will be one of the following:
N - indicates a newly added property/element
D - indicates a property/element was deleted
E - indicates a property/element was edited
A - indicates a change occurred within an array
path - the property path (from the left-hand-side root)
lhs - the value on the left-hand-side of the comparison (undefined if kind === 'N')
rhs - the value on the right-hand-side of the comparison (undefined if kind === 'D')
index - when kind === 'A', indicates the array index where the change occurred
item - when kind === 'A', contains a nested change record indicating the change that occurred at the array index
关于node.js - 将对象的更新从客户端发送到 nodejs,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49065647/