On Loopback中,如何以编程方式将数据添加到发布的内容(如UserID和Date)?

问题描述:

假设您创建了一个应用程序,允许注册用户通过Loopback API将内容发布到数据库(MySQL)。现在,您将如何拦截发布的内容来填写一些字段,例如: - 基于访问令牌的用户ID? - 当前日期/时间?On Loopback中,如何以编程方式将数据添加到发布的内容(如UserID和Date)?

使用远程挂钩将是正确的方式。这里是远程挂钩的例子,它会在保存记录之前添加创建日期,修改日期和userId。创建日期和ownerId只有在新记录时才会设置,并在更新呼叫上设置修改日期。

通用/模型/ model.js

'use strict'; 

module.exports = function(Model) { 
    // Set dates and userId before saving the model 
    Model.observe('before save', function setAutoData(context, next) { 
     if (context.instance) { 
      if(context.isNewInstance) { 
       context.instance.created = Date.now(); 
       context.instance.ownerId = context.options.accessToken.userId; 
      } 
      context.instance.modified = Date.now(); 
     } 
     next(); 
    });  
}; 
+0

嗨Harpreet!这对我有效!非常感谢! –

可以使用remote hooks

例如拦截从客户端传来的数据:

Model.CustomCreate = function(data, cb){ 
    Mode.create(data, cb); 
}; 

Model.beforeRemote('CustomCreate', function(ctx, instance, next){ 
    ctx.args.data.changeDate = new Date(); 
    var token = ctx.req.headers.token; // or however you set that 
    app.models.User.findByToken(token, function(err, account){ 
    if(err) return next(err); 
    ctx.args.data.userId = account.id; 
    next(); 
    });  
}); 

我该令牌在请求头保存在你的方式上面考虑英寸

+0

嗨易卜拉欣,谢谢! Loopback是我的新手。为了遵循你的指令,我应该创建一个带有我的模型名称(比如说文章)的JS文件,并将其放在common/models/article.js文件夹中?之后,我将代码添加到由module.exports包围的文件中,然后使用我的模型名称替换代码中的单词Model,对吗?另外,你将如何获得基于访问令牌的用户ID? –

+0

@FabioNolasco嗨法比奥。 NP。以自己的方式创建模型会更好。您可以通过命令'lb model'创建模型。请按照[此说明](https://loopback.io/doc/en/lb3/Getting-started-with-LoopBack.html) –

+0

是的,没错。用户标识怎么样?在那个时候,如何根据从http标头提供的访问标记得到它? –