Loopback Connector REST API

后端 未结 2 589
萌比男神i
萌比男神i 2020-12-19 18:48

How to create an external API on Loopback?

I want to get the external API data and use it on my loopback application, and also pass the input from my loopback to ext

2条回答
  •  猫巷女王i
    2020-12-19 19:22

    You gonna need https module for calling external module inside loopback.

    Suppose you want to use the external API with any model script file. Let the model name be Customer

    Inside your loopback folder. Type this command and install https module.

    $npm install https --save
    

    common/models/customer.js

    var https = require('https');
    
    Customer.externalApiProcessing = function(number, callback){
       var data = "https://rest.xyz.com/api/1";
       https.get(
         data,
         function(res) {
            res.on('data', function(data) {
              // all done! handle the data as you need to
    
              /*
                 DO SOME PROCESSING ON THE `DATA` HERE
              */
    enter code here
              //Finally return the data. the return type should be an object.
              callback(null, data);
            });
         }
       ).on('error', function(err) {
           console.log("Error getting data from the server.");
           // handle errors somewhow
           callback(err, null);
       }); 
      }
    
    
    
    
    //Now registering the method
    Customer.remoteMethod(
        'extenalApiProcessing', 
        {
          accepts: {arg: 'number', type: 'string', required:true},
          returns: {arg: 'myResponse', type: 'object'}, 
          description: "A test for processing on external Api and then sending back the response to /externalApiProcessing route"
        }
    )
    

    common/models/customer.json

     ....
     ....
     //Now add this line in the ACL property.
     "acls": [
    
        {
          "principalType": "ROLE",
          "principalId": "$everyone",
          "permission": "ALLOW",
          "property": "extenalApiProcessing"
        }
      ]
    

    Now explore the api at /api/modelName/extenalApiProcessing

    By default its a post method.

    For more info. Loopback Remote Methods

提交回复
热议问题