在环回中写保护属性

我有一个types为json的有效载荷的模型。

content.json

... "properties": { "payload": { "type": "object", "required": true } }, ... 

我想在updateAttributes被调用时保护它的一部分不被覆盖。

  Content.beforeRemote('prototype.updateAttributes', function (ctx, unused, next) { if (ctx.instance && ctx.instance.contentTypeId === 'folder') { // TODO: Do not allow direct modification of the folder items (should use exposed API). // Strip writes to payload.items and payload.itemIds } next(); }); 

达到这个目标的最好方法是什么?

也不

 delete ctx.req.body.payload.items 

也不

 delete ctx.args.data.payload.items 

也不

 delete ctx.instance.payload.items 

做我想要的。

我必须完全重写updateAttributes方法吗?

根据我的经验,没有其他的方法来克服你的问题,而不会重写updateAttributes

boot文件夹中有一个名为override-defaults.js的文件,代码如下。

 var overrideUpdateAttributes = function (Model, fields) { var updateAttributes = Model.prototype.updateAttributes; Model.prototype.updateAttributes = function (data, cb) { data = _.omit(data, fields); if (Object.keys(data).length) { updateAttributes.call(this, data, cb); } else { cb(utils.createError('Request body cannot be empty', 400)); } }; }; module.exports = function (app) { overrideUpdateAttributes(app.models.UserUser, ['id', 'created', 'lastLogin', 'deleted', 'deletedAt']); }; 

假设你调用的有效载荷代表了要更新的目标模型,你可以强制将属性设置为undefined,它将被忽略:

 ctx.instance.items = undefined; 

如果有效载荷是模型的一个属性,并且items是一个嵌套属性,那么要么完全忽略有效载荷(将其设置为undefined),要么将原始模型有效载荷属性和新的属性剥离后对其进行深度合并。