[英]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.