RSA
RSA

Reputation: 1449

How to make something like remote method on loop-back middleware?

In fallowing code i want to make something like remote method on middleware in loopback to post values to calculate for example: in app :

submitForm() {
    let headers = new Headers(
      {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      });
    let options = new RequestOptions({ headers: headers });

    let data = JSON.stringify({
      Value1: this.form.value1,
      Value2: this.form.value2,
      Value3: this.form.value3
    });   
    console.log(data);

    let url = 'http://localhost:3000/calculate';
console.log(url);
    return new Promise((resolve, reject) => {
      this.http.post(url, data, options)
        .toPromise()
        .then((response) => {
          console.log('API Response : ', response.status);
          resolve(response.json());
        })
        .catch((error) => {
          console.error('API Error : ', error.status);
          console.error('API Error : ', JSON.stringify(error));
          reject(error.json());
        });
    });
  }

and in remote method or anything like that, I used such this code but totally fails:

module.exports = function () {
    accepts: [{arg: 'val1', type: 'number'},{arg: 'val2', type: 'number'}],
  returns: {arg: val1+val2, type: 'number'},
  http: {path: '/calculate', verb: 'get'}
});
};

Upvotes: 0

Views: 521

Answers (2)

EramSa
EramSa

Reputation: 130

This is my solution for my problem:

As you can see there is no parameters shown on URL and i think this may be secure I'm not expert one but I guess help to you:

   module.exports = function(server) {
        const https = require('https');
        var request = require('request');

    return function verification(req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); 
        res.setHeader('Access-Control-Allow-Credentials', true);
            var request;
            var response;
            var body = '';
            // When a chunk of data arrives.
            req.on('data', function (chunk) {
                // Append it.
                body += chunk;
            });
            // When finished with data.
            req.on('end', function () {
                // Show what just arrived if POST.
                if (req.method === 'POST') {
                    console.log(body);
                }
                // Which method?
                switch (req.method) {
                    case 'GET':
                         Verify url and respond with appropriate data.
                         handleGet(req, res);
                         Response has already been sent.
                         response = '';
                         break;
                    case 'POST':
                        // Verify JSON request and respond with stringified JSON response.
                        response = handlePost(body);
                        break;
                    default:
                        response = JSON.stringify({ 'error': 'Not A POST' });
                        break;
                }
                // Send the response if not empty.
                if (response.length !== 0) {
                    res.write(response);
                    res.end();
                }
                // Paranoid clear of the 'body'. Seems to work without
                // this, but I don't trust it...
                body = '';
            });
            // If error.
            req.on('error', function (err) {
                res.write(JSON.stringify({ 'error': err.message }));
                res.end();
            });
            //
        };
        function handlePost(body) {
            var response = '';
            var obj = JSON.parse(body);
            // Error if no 'fcn' property.
            if (obj['fcn'] === 'undefined') {
                return JSON.stringify({ 'error': 'Request method missing' });
            }
            // Which function.
            switch (obj['fcn']) {
                // Calculate() requres 3 arguments.
                case 'verification':
                    // Error if no arguments.
                    if ((obj['arg'] === 'undefined') || (obj['arg'].length !== 3)) {
                        response = JSON.stringify({ 'error': 'Arguments missing' });
                        break;
                    }
                    // Return with response from method.
                    response = verification(obj['arg']);
                    break;
                default:
                    response = JSON.stringify({ 'error': 'Unknown function' });
                    break;
            }
            return response;
        };
        function verification(arg) {
            var n1 = Number(arg[0]);
            var n2 = Number(arg[1]);
            var n3 = Number(arg[2]);
            var result;
            // Addem up.
            result = n1 + n2 + n3;
            // Return with JSON string.
            return JSON.stringify({ 'result': result });
        };
        };

Upvotes: 1

ChamalPradeep
ChamalPradeep

Reputation: 429

Example remote method that I used correctly

module.exports = function (TeamRole) {
      TeamRole.getUsers = function (id, cb) {
        TeamRole.find({
          where: {
            teamId: id
          }
        }, function (err, users) {
          cb(null, users);
        });
      };

      TeamRole.remoteMethod('getUsers', {
        accepts: {
          arg: "id",
          type: "string",
          required: true
        },
        returns: {
          arg: 'users',
          type: 'Array'
        },
        http: {
          path: '/:id/users',
          verb: 'get'
        }
      });
}

As above example you can define remote method correctly to achieve you task.

cheers.

Upvotes: 3

Related Questions