Rad*_*ion 1 rest node.js express loopbackjs
我要弄清楚的是如何获取当前经过身份验证的用户的ID,以及如何在数据库中将记录创建为其他模型的外键时使用该ID?
更具体地说,我需要获取当前经过身份验证的用户(模型:CommonUser)的ID,并在创建新事件时将该ID用作FK。
关系:
我已经基于称为CommonUser的用户模型创建了一个模型。普通用户有很多事件。事件属于普通用户。
因此,Event具有一个名为commonUserId的外键。
如何获取用户ID并在插入时使用该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": {}
}
Run Code Online (Sandbox Code Playgroud)
事件
{
"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": {}
}
Run Code Online (Sandbox Code Playgroud)
事件查询
{
"name": "EventLookUp",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Run Code Online (Sandbox Code Playgroud)
如果我能指出正确的方向,那就太好了。阅读文档很难找到答案。我想我需要在插入并设置事件模型属性之前使用操作挂钩?到目前为止,环回的最佳做法是什么?
小智 5
使用环回默认用户/登录api以用户身份登录时,在环回swagger中,您将获得访问令牌对象作为响应。您可以复制访问令牌的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();
});
Run Code Online (Sandbox Code Playgroud)
对于事件obj的updateAttributes:
Event.observe('before save', function updateUserId(ctx, next) {
let userId = ctx.options.accessToken.userId;
if (ctx.currentInstance) {
ctx.currentInstance.commonUserId = userId;
}
next();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
554 次 |
| 最近记录: |