访问Parse.com Cloud Code beforeSave函数中的原始字段

Accessing original field in Parse.com Cloud Code beforeSave function

本文关键字:原始 字段 函数 beforeSave Parse com Cloud Code 访问      更新时间:2023-09-26

最终目标是使用云代码中的beforeSave函数检测现有Parse对象和传入更新之间的更改。

从parse.com上提供的云代码日志中,可以看到beforeSave的输入包含一个名为original的字段和另一个称为update的字段。

云代码日志:

Input: {"original": { ... }, "update":{...}

我想知道我们是否以及如何访问原始字段,以便在保存之前检测不断变化的字段。

注意,我已经尝试了几种方法来解决这个问题,但没有成功:

  • 使用(object).changedAttributes()
  • 使用(object).previousAttributes()
  • 获取现有对象,然后用新数据更新

request.object.changedAttributes()上的注释:在beforeSave和afterSave中使用时返回false——有关更多详细信息,请参阅下面的内容:

before_save的日志——为可读性总结:

Input: { original: {units: '10'}, update: {units: '11'} }
Result: Update changed to { units: '11' }
[timestamp] false <--- console.log(request.object.changedAttributes())

对应after_save:的日志

[timestamp] false <--- console.log(request.object.changedAttributes())

changedAttributes()存在问题。它似乎一直都是假的——或者至少在beforeSave中是这样,在那里它是合理需要的。(见这里,以及其他类似的帖子)

这里有一个通用的工作来做changedAttributes应该做的事情

// use underscore for _.map() since its great to have underscore anyway
// or use JS map if you prefer...
var _ = require('underscore');
function changesOn(object, klass) {
    var query = new Parse.Query(klass);
    return query.get(object.id).then(function(savedObject) {
        return _.map(object.dirtyKeys(), function(key) {
            return { oldValue: savedObject.get(key), newValue: object.get(key) }
        });
    });
}
// my mre beforeSave looks like this
Parse.Cloud.beforeSave("Dummy", function(request, response) {
    var object = request.object;
    var changedAttributes = object.changedAttributes();
    console.log("changed attributes = " + JSON.stringify(changedAttributes));  // null indeed!
    changesOn(object, "Dummy").then(function(changes) {
        console.log("DIY changed attributes = " + JSON.stringify(changes));
        response.success();
    }, function(error) {
        response.error(error);
    });
});

当我通过客户端代码或数据浏览器将someAttributeDummy实例上的数字列)从32更改为1222时,日志显示如下:

I2015-06-30T20:22:39.886Z]更改的属性=错误

I2015-06-30T20:22:39.988Z]DIY更改了属性=[{"oldValue":32,"newValue":1222}]