loopback - 在 POST 响应中包含 Loopback 关系
问题描述
我有一个工作聊天室环回项目,它也利用了 Socket.IO。
创建消息(POST 到 Loopback REST API)后,我需要包含“创建者”关系的响应。
这在使用 GET 时效果很好,但我不能包含与 POST 响应的关系。
我确定这是一个简单的远程挂钩,但我被卡住了......
任何帮助是极大的赞赏!
"relations": {
"creator": {
"type": "belongsTo",
"model": "Person",
"foreignKey": "",
"options": {
"nestRemoting": true
}
},
"event": {
"type": "belongsTo",
"model": "Event",
"foreignKey": "",
"options": {
"nestRemoting": true
}
}
},
解决方案
有两种方法可以使用Loopback 2.x
or 3.x
(不确定 Loopback 4.x)。
假设我们有以下"Note"
模型:
{
"name": "Note",
"properties": {
"title": {
"type": "string",
"required": true
},
"content": {
"type": "string"
},
"userId": {
"type": "number"
}
},
"relations": {
"user": {
"type": "belongsTo",
"model": "User",
"foreignKey": "userId"
}
}
}
现在,当您( ) a 注意时,要在响应中包含"user"
属性(它是 的belongsTo
关系),您有两个选择。Note
create
POST
选项 #1(推荐):创建自定义远程方法并在模型的脚本文件中隐藏默认方法。在这种情况下,您的note.js
文件应类似于:
module.exports = function (Note) {
// Hide the default 'create' remote method
Note.disableRemoteMethod('create', true);
// Add a custom 'customCreate' remote method
Note.remoteMethod('customCreate', {
description: 'Create a new instance of the model and persist it into the data source.',
accessType: 'WRITE',
accepts: [
{
arg: 'data',
type: 'object',
model: 'Note',
allowArray: true,
description: 'Model instance data',
http: { source: 'body' },
},
{ arg: 'options', type: 'object', http: 'optionsFromRequest' },
],
returns: { arg: 'data', type: 'Note', root: true },
http: { verb: 'post', path: '/' },
isStatic: true,
});
Note.customCreate = function (data, options, cb) {
Note.create(data, options, function(err, newObj) {
if (err) {
cb(err);
}
else {
// here we try to load the user value
newObj.user(function (err, user) {
if (user) {
// if we found a user we add it to __data, so it appears in the output (a bit hacky way)
newObj.__data.user = user;
}
cb(err, newObj);
});
}
});
};
};
我建议使用此选项,因为您只需对环回模型的默认逻辑进行最小更改即可实现所需的功能,即所有默认方法(如 create、upsert 等)继续具有默认行为。
选项 2:使用 'after save'操作挂钩(小心这种方法,因为它改变了 create、upsert、upsertWithWhere 和其他默认方法的工作方式)
在这种情况下,您的 note.js 文件应类似于:
module.exports = function (Note) {
Note.observe('after save', function (ctx, next) {
ctx.instance.user(function (err, user) {
ctx.instance.__data.user = user;
next();
});
});
};
第二个选项的代码更少,但正如我之前提到的,你应该非常小心地使用它,因为它会改变模型默认“create”方法的行为。即每次调用 Model.create、Model.upsert 等时都会执行操作。当您在挂钩'after save'
中添加额外的选择查询时,它也会减慢这些操作。'after save'
推荐阅读
- php - 如何使用php中的数据库记录正确循环和创建json
- python - 例如,= mnist_train.take(1) 是什么?
- heroku - 为什么我的烧瓶命令不能在 Heroku 上运行?
- python - 是否可以编写一个带有隐藏方法的 Python 类,该方法只有在设置了特定属性时才能调用?
- python - 在类别数组上细分ndarray
- java - Java Socket 不允许摆动框架出现
- java - 抛出异常以强制退出递归有效吗?
- visual-studio-code - 在 VS Code 中创建新文件的替代方法?
- postgresql - 首先尝试更新的 INSERT ... ON CONFLICT 相当于什么?
- prism - Fluent.Ribbon 的 RegionAdapter