【问题标题】:Loopback - how to get id of user and insert into related model? (hasMany)Loopback - 如何获取用户 ID 并插入相关模型? (有很多)
【发布时间】:2018-07-07 16:05:17
【问题描述】:

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

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

关系:

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

所以 Event 有一个名为 commonUserId 的外键。

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

就建立关系而言,我会认为这将作为过程的一部分自动进行?这是不正确的吗?

为了使事情复杂化,我有一个事件查找表(我接下来会担心这个,所以不要觉得有必要深入研究),因为事件也通过事件查找具有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": {}
}

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

【问题讨论】:

    标签: node.js rest express loopbackjs


    【解决方案1】:

    在 loopback swagger 中,当您使用 loopback 的默认 users/login api 以用户身份登录时,您将获取访问令牌对象作为响应。您可以复制访问令牌的 id 并粘贴到 swagger 右上角的框中并设置访问令牌。因此在内部,您的访问令牌设置在环回中,并且对于来自 swagger 的每个请求,环回都会将访问令牌与请求一起附加。通过这种方式,您可以在远程方法中从 ctx(context) 获取访问令牌。

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

    Event.observe('before save', function updateUserId(ctx, next) {
    
      let userId = ctx.options.accessToken.userId;`
    
      if (ctx.instance) {
        ctx.instance.commonUserId = userId;
      }
      next();
    });
    

    对于事件 obj 的 updateAttributes:

    Event.observe('before save', function updateUserId(ctx, next) { 
    
      let userId = ctx.options.accessToken.userId; 
    
      if (ctx.currentInstance) { 
        ctx.currentInstance.commonUserId = userId;
      } 
      next(); 
    });
    

    【讨论】:

    • 感谢您的回复!我仍在更深入地学习环回的复杂性,老实说 javascript。我来自面向对象编程和过程 PHP 编程,我需要一些时间来巩固函数式编程的思想。将函数作为对象(回调)传递会伤害我的大脑:D
    • 哦,没有线程很奇怪。我已经习惯了线程,我什至没有考虑到底发生了什么。必须异步编程肯定是一种不同的心态!
    【解决方案2】:

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

    无论如何,我在“/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();
        });
    
    };
    

    如果有人不介意解释上下文来自哪里以及它是如何填充的,那就太棒了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      相关资源
      最近更新 更多