javascript - 环回中的写保护属性

标签 javascript node.js loopbackjs

我有一个带有 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']);
};

关于javascript - 环回中的写保护属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233520/

相关文章:

javascript - 从网页附加横幅代码

node.js - 在 Ubuntu 中将 Node.js 脚本作为服务运行的最佳方式是什么?

javascript - Google 表格行作为数组

Node.js 错误 - AssertionError [ERR_ASSERTION] : pattern should not use global or sticky mode . .. 重新安装包后

javascript - Mongoose 是否可以至少拥有一项所需的属性?

angularjs - 在带有环回后端的 Angular 应用程序中通过 facebook 登录

node.js - 使用 mongodb 环回中的嵌套(嵌入式)树模型

node.js - 如何在环回中生成用户事件日志

javascript - Vuejs 2.4.4 + Laravel 5.5 渲染来自 api 调用的响应

javascript - 监控用户 session 以防止编辑冲突