Loopback - 如何获取用户 ID 并插入相关模型? (有很多)

Loopback - how to get id of user and insert into related model? (hasMany)

我想弄清楚的是如何获取当前经过身份验证的用户的 ID 并在数据库中创建记录时将其用作不同模型的外键?

更具体地说,我需要获取当前经过身份验证的用户的 ID(模型:CommonUser)并在创建新事件时使用该 ID 作为 FK。

关系:

我创建了一个基于名为 CommonUser 的用户模型的模型。普通用户有很多事件。活动属于普通用户。

所以 Event 有一个名为 commonUserId 的 foreignKey。

如何获取用户 ID 并在插入时使用它?

我原以为就建立关系而言,这将是自动过程的一部分?这不正确吗?

另外,为了使事情复杂化,我有一个事件查找 table(接下来我会担心这个,所以不必深入研究)因为事件也通过事件查找具有 AndBelongsToMany。

用户

{
  "name": "CommonUser",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {},
  "validations": [],
  "relations": {
    "events": {
      "type": "hasMany",
      "model": "Event",
      "foreignKey": "eventId",
      "through": "EventLookUp"
    },
    "friends": {
      "type": "hasMany",
      "model": "CommonUser",
      "through": "Friend",
      "foreignKey": "friendId"
    }
  },
  "acls": [],
  "methods": {}
}

事件

{
  "name": "Event",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string"
    },
    "radius": {
      "type": "number",
      "default": 50
    },
    "status": {
      "type": "number"
    },
    "location": {
      "type": "geopoint",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "owner": {
      "type": "belongsTo",
      "model": "CommonUser",
      "foreignKey": "commonUserId"
    },
    "commonUsers": {
      "type": "hasAndBelongsToMany",
      "model": "CommonUser",
      "foreignKey": "ownerId",
      "through": "EventLookUp"
    },
    "galleries": {
      "type": "hasOne",
      "model": "Gallery",
      "foreignKey": ""
    },
    "photos": {
      "type": "hasMany",
      "model": "Photo",
      "foreignKey": "",
      "through": "Gallery"
    }
  },
  "acls": [],
  "methods": {}
}

事件查找

{
  "name": "EventLookUp",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

如果我能指出正确的方向,那就太好了。通读文档很难找到答案。 我认为我需要在插入和设置事件模型属性之前使用操作挂钩?就此而言,环回的最佳实践是什么?

我找到了解决方案,但我不确定这是否是最佳做法,或者是否有更好的方法来处理这个问题。

无论如何,我在“/common/models/event.js”中创建了一个操作挂钩,显然您可以访问该挂钩中的上下文。

如果有更好的方法,我想知道。

'use strict';
module.exports = function (Event) {


    Event.observe('before save', function updateForeignKeyCommonUserId(ctx, next) {

        // console.log(ctx.options);
        /* WHAT Options Looks Like */
        // { accessToken:
        // { id: 'Z20R1RsnumWEdDzR3TyCCbmZ0DTp4tOh2cviU6JGsrlNIYCs3KchQ7mdAnhTc1VQ',
        //     ttl: 1209600,
        //     created: 2018-06-26T17:41:28.298Z,
        //     userId: 3 },
        // authorizedRoles: {} }
        // console.log("THE USER ID IS: ");
        // console.log(ctx.options.accessToken.userId); // Current User Id

        var userId = ctx.options.accessToken.userId;

        // So appearently "the context provides either an instance property or a pair of data and where properties"
       // @todo: find out why there can be a 'instance' or 'data'. 
        if (ctx.instance) {
            ctx.instance.commonUserId = userId; // instance
        } else {
            ctx.data.commonUserId = userId; // data
        }
        next();
    });

};

如果有人不介意解释上下文的来源以及填充方式,那就太棒了!

当您使用环回的默认 users/login api 作为用户登录时,在环回 swagger 中,您将获得访问令牌对象,因为 response.You 可以复制访问令牌的 ID 并粘贴到swagger 右上角的框并在内部设置访问 token.Thus 您的 accesstoken 设置在 loopback 中,对于来自 swagger 的每个请求,loopback 将访问令牌与 request.In 一起附加,这样您可以获得远程方法中来自 ctx(context) 的访问令牌。

对于create,findOrCreate,保存一个事件对象:

Event.observe('before save', function updateUserId(ctx, next) {

  let userId = ctx.options.accessToken.userId;`

  if (ctx.instance) {
    ctx.instance.commonUserId = userId;
  }
  next();
});

对于事件对象的更新属性:

Event.observe('before save', function updateUserId(ctx, next) { 

  let userId = ctx.options.accessToken.userId; 

  if (ctx.currentInstance) { 
    ctx.currentInstance.commonUserId = userId;
  } 
  next(); 
});