Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom schema for custom remote methods on Strongloop

I'm newbie on Strongloop and I can't find information for how to customize my response class (model schema for a object I built) and I don't know how to show on the API explorer the object with custom data.

Capture for strongloop api explorer

For example, I have a custom remote method called score

POST /Challenges/score

I want to show for the parameter data a custom model schema instead of single parameters, not the Model Schema for Challenge, the data on the body have all the parameters and show to the user on the Data Type: Model Schema, is this possible?

{
  "id": "string",
  "limit": 0,
  "order": "string",
  "userId": "string"
}

On the other side, in Response Class I want to show the schema for the response object. Something like this:

{
  "id":"string",
  "userId":"string",
  "user": {},
  "totalScore":0,
  "tags": []
}

I looked different questions (this and this), but can not find something to solve this issues.

Update

Here is the definition of the remote method

Challenge.remoteMethod('score', {
    accepts: { arg: 'data', type: 'object', http: { source: 'body' } },
    returns: {arg: 'scores', type: 'array'},
    http: {path: '/score', verb: 'post'}
});
like image 563
jrltt Avatar asked Mar 04 '16 09:03

jrltt


1 Answers

I believe you might have gone through the official docs of strongloop. If not, here is the link that explains the remote methods and their accepted data types. https://docs.strongloop.com/display/public/LB/Remote+methods

Assuming your custom object is Challenge, to show the object in response you have to specify the type( the type can be one of the loopback's data type or you custom model). So to return Challenge you have to add following code :

Challenge.remoteMethod('score', {
    accepts: { arg: 'data', type: 'object', http: { source: 'body' } },
    returns: {arg: 'scores', type: 'Challenge', root: true},
    http: {path: '/score', verb: 'post'}, 
});

The second arrow that you have specified is the default values that you want to try out with your API call. You can pass any custom string with default as the key. For example, if you want to pass some object :

Challenge.remoteMethod('score', {
    accepts: {
        arg: 'data',
        type: 'object',
        default: '{
            "id": "string",
            "userId": "string",
            "user": {},
            "totalScore": 0,
            "tags": []
        }',
        http: {
            source: 'body'
        }
    },
    returns: {
        arg: 'scores',
        type: 'Challenge'
    },
    http: {
        path: '/score',
        verb: 'post'
    }
});

So, for response you can not customize the model. But to pass default values you can put anything in the string format.

like image 142
Ankit Singh Avatar answered Sep 28 '22 18:09

Ankit Singh