简体   繁体   中英

Loopback: Executing a generated method using JavaScript

I want to use a generated method (specifically __get__accessTokens ) in JavaScript but I don't know how. I can test that this functionality (getting the tokens of a user) works fine using the REST API Explorer but I can't find any examples of how to access generated methods programmatically and what's their signature. An example of what I need ( Member extends the default User model):

models/member.js

 module.exports = function(Member) {
      Member.__get__accessTokens(...)

      // or if I have a specific user (e.g. after executing findById)
      Member.findById(id, function(err, member) {
           member.__get__accessTokens(...)      
      });          
 }

You can user afterRemote and beforeRemote methods for this.

  module.exports  = function(Member) {
      Member.beforeRemote("__your methods__", function(ctx, inst, next){
        var accessToken = ctx.req.accessToken;
        app.models.Member.findById(accessToken.userId, function(err, usr){
          //Process here....
        }
      next();
     }
    }

OR

You can use current context. https://docs.strongloop.com/display/public/LB/Using+current+context

You can access it from the context:

module.exports = function(Product) {  
    var app = require('../../server/server')

    Product.afterRemote('create', function( ctx, modelInstance, next) {
        var accessToken = ctx.req.accessToken

        // get Customer (User) by using the user id in token object
        app.models.Customer.findById(accessToken.userId, function(err, user) {
            modelInstance.createdBy = user.username
            next()
        })
    })
}

I use this portion of code to capture the username who create the model through REST API. Full explanation can be found in here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM