[英]Loopback REST findById doesn't work well
我想通过REST API使用findById
函数。
我将“ID”定义为全部由数字构成的字符串。
我试图通过ID找到,系统似乎认出它的号码。
当ID是“9007199254740992”的最大数字时,我无法使用它 - 最大整数。
我想将ID用作字符串。
请告诉我如何解决这个问题。
谢谢,
- 跟进 -
我的计划如下。
模型 - sample-model.json
{
"name": "SampleModel",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"id": {
"type": "string",
"id": "true",
"required": true,
"doc": "MODEL ID"
},
"prop1": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
当我通过REST API访问findById
函数时,我总是得到以下调试消息。
strong-remoting:shared-method - findById - invoke with +11ms [ 9007199254740992, undefined, [Function: callback] ]
strong-remoting:shared-method - findById - result null +25ms
strong-remoting:rest-adapter Invoking rest.after for SampleModel.findById +6ms
express:router restRemoteMethodNotFound : /api/SampleModels/9007199254740993 +143ms
express:router restUrlNotFound : /api/SampleModels/9007199254740993 +8ms
express:router restErrorHandler : /api/SampleModels/9007199254740993 +2ms
strong-remoting:rest-adapter Error in GET /SampleModels/9007199254740993: Error: Unknown "SampleModel" id "9007199254740993".
我自己解决了我的问题。
我们可以使用“接受”选项定义远程方法接受的参数。
内置的findById
函数在PersistedModel中定义如下:
accepts: [
{ arg: 'id', type: 'any', description: 'Model id', required: true,
http: {source: 'path'}},
{ arg: 'filter', type: 'object',
description: 'Filter defining fields and include'}
],
当type
定义为any
, id
会被HttpContext.coerce
函数更改为number - 如果id
仅包含数字字符。
为了解决这个问题,我定义了SampleModel.findByIdCustom
并创建了另一个远程方法,如下所示:
SampleModel.js
SampleModel.findByIdCustom = function(id, filter, cb) {
SampleModel.findById(id, filter, cb);
}
//Define remote method
SampleModel.remoteMethod(
'findByIdCustom',
{
description: 'Find a model instance by id from the data source.',
accessType: 'READ',
accepts: [
{ arg: 'id', type: 'string', description: 'Model id', required: true,
http: {source: 'path'}},
{ arg: 'filter', type: 'object',
description: 'Filter defining fields and include'}
],
returns: {arg: 'data', type: 'user', root: true},
http: {verb: 'get', path: '/:id'},
rest: {after: SampleModel.convertNullToNotFoundError},
isStatic: true
}
);
//disable built-in remote method
SampleMethod.disableRemoteMethod('findById', true);
谢谢,
只需将idInjection
设置为false
(以便环回不会自动向模型添加id属性),然后使用以下参数定义属性:
{
"idInjection": false,
"properties": {
"id": {
"type": "string",
"id": true,
"generated": true
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.