我有一个工作的聊天室环回项目,它也使用Socket.IO。
一旦我创建了一个消息(POST到Loopback REST API),我需要包含'creator'关系的响应。
这在使用GET时工作正常,但我不能包含与POST响应的关系。
我确定这是一个简单的遥控钩,但我被卡住了......
任何帮助是极大的赞赏!
"relations": {
"creator": {
"type": "belongsTo",
"model": "Person",
"foreignKey": "",
"options": {
"nestRemoting": true
}
},
"event": {
"type": "belongsTo",
"model": "Event",
"foreignKey": "",
"options": {
"nestRemoting": true
}
}
},
如何使用Loopback 2.x
或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"
}
}
}
现在,要包括"user"
属性(这是belongsTo
的Note
关系),当你create
(POST
)注意时你有两个选择。
选项#1(推荐):创建一个custom remote method并隐藏模型脚本文件中的默认方法。在这种情况下,您的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:使用'保存后'operation hook(小心这种方法,因为它改变了创建,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();
});
});
};
第二个选项的代码较少,但正如我之前提到的,你应该非常小心地使用它,因为它会改变模型的默认“创建”方法的行为。即每次调用Model.create,Model.upsert等时都会执行'after save'
动作。当你在'after save'
钩子中添加额外的select查询时,它也会减慢这些操作。