Search code examples
node.jsloopbackjs

search api in loopback nodejs


I have a need to implement this api in loopback nodejs

https://myapi.com/part_numbers?part_number=1245,6787,89490,940044...

Any ideas on how to go about it ? The path after part_number should accept atleast 100 partnumbers and then return me the result.

All the documentation that i have looked at in loopback talks abut only sending a get request to something like https://myapi.com/part_numbers?part_number=1245 but not about sending for multiple comma separated values

Any ideas on how do i build this endpoint using loopback and nodejs I am using mysql as the backend datastore.


Solution

  • Disclaimer: I am a maintainer of LoopBack and co-author of the pull request adding support for character-delimited arrays in input arguments.

    LoopBack provides a feature flag to enable comma-delimited array values in input arguments, this flag was added by https://github.com/strongloop/strong-remoting/pull/142. (Unfortunately it's not documented yet.)

    How to use it:

    1) Configure allowed delimiters in your server/config.json:

    {
      "restApiRoot": "/api",
      // ...
      "rest": {
        "handleErrors": false,
        // ADD THE FOLLOWING LINE
        "arrayItemDelimiters": [","],
        // original content - keep it around:
        "normalizeHttpPath": false,
        "xml": false
      },
      // ...
    }
    

    2) Define a custom remote method (see docs) accepting an argument of type "array of numbers". For example, assuming you have a model called PartNumbers already defined:

    PartNumbers.get = function(numbers) {
      // replace this code with your implementation
      // here, we simply return back the parsed array
      return Promise.resolve(numbers);
    };
    
    PartNumbers.remoteMethod('get', {
      accepts: {
        arg: 'part_numbers',
        type: ['number'],
        required: true,
      },
      // modify "returns" to match your actual response format
      returns: {
        arg: 'data',
        type: 'object',
        root: true,
      },
      http: {verb: 'GET', path: '/'},
    });
    

    3) Start you application, open API Explorer at http://localhost:3000/explorer and give your new method a ride!