更新前设置 属性

Set property before update

我阅读了 Operation hooks 并理解了 "not tied to a particular method" 的概念。所以我想知道是否可以在更新模型之前设置 属性。

我的用户模型中有一个 updatedAt 属性,我想在对 PUT 动词的所有调用中将其设置为 new Date();

我没有尝试任何东西,因为我没有在文档或 Whosebug 中找到答案。

谢谢。

使用operation hooks:

module.exports = User => {
  User.observe('before save', (ctx, next) => {
    if (ctx.instance) {
      ctx.instance.updatedAt = new Date()
    } else {
      ctx.data.updatedAt = new Date()
    }
    next()
  })
}

如果您想将此通用逻辑应用于模型集,mixins 通常是一个可行的方法。

module.exports = (Model, options) => {
  Model.defineProperty('updatedAt', { type: Date, default: '$now' })

  Model.observe('before save', (ctx, next) => {
    if (ctx.instance) {
      ctx.instance.updatedAt = new Date()
    } else {
      ctx.data.updatedAt = new Date()
    }
    next()
  })
}

如果您不想自己实现,可以使用 npm package