Search code examples
javascriptphpjqueryloopbackjsstrongloop

Strongloop - Execute PHP with model.js


I'm trying to execute PHP within a loopback model. When visiting myapi:3000/api/Door/open I'd like it to run the PHP file containing a function.

I have the /Door/open added as a remote method and it shows up in swagger.ui, the api returns "message": "createElement is not defined", even though jquery is included.

Here is my doors.js showing the remote method setup:

  module.exports = function(Door) {
  Door.open = function(id, cb) {
    var script = createElement('script');
    script.src = 'http://code.jquery.com/jquery-2.1.4.min.js';
    script.type = 'text/javascript';
    getElementsByTagName('head')[0].appendChild(script);
    $.ajax({
      url: "http://192.168.10.139/Facility/doorfunc_dynamic.php?dpip=192.168.10.249&doorid=3&func=unlock"
    }).done(function(data) {
      console.log(data);
    });
  };
  Door.remoteMethod(
    'open',
    { 
      description: 'Open a door by id',
      accepts: {args: 'id', type: 'number', name: 'id', description: 'Door id'},
      returns: {arg: 'open', type: 'string'},
      http: {path: '/open', verb: 'get'}       
    }
  );
};

Does anyone know how to resolve this? I have tried adding a static page within the client folder, however it does not show within the swagger.ui explorer.


Solution

  • If you want to perform only http request, you can use request package.

    var request = require('request');
    module.exports = function(Door) {
        Door.open = function(id, cb) {
            request('http://192.168.10.139/Facility/doorfunc_dynamic.php?dpip=192.168.10.249&doorid=3&func=unlock', 
                function(error, response, body) {
                    if (!error && response.statusCode == 200) {
                        console.log(body);
                    }
            });
        };
        Door.remoteMethod(
            'open',
            { 
                description: 'Open a door by id',
                accepts: {args: 'id', type: 'number', name: 'id', description: 'Door id'},
                returns: {arg: 'open', type: 'string'},
                http: {path: '/open', verb: 'get'}       
            }
          );
        };
    

    Hope it solves your problem.