index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. module.exports = function (express, helperUrl, rpcClientClassName, remoteObj) {
  2. var Mustache = require('mustache');
  3. var fs = require('fs');
  4. var rpcRouter = express.Router();
  5. rpcRouter.get('/test', function (req, res) {
  6. res.send(200, "test successful...");
  7. });
  8. rpcRouter.get(helperUrl, function (req, res) {
  9. var port = (process.env.lrs_PORT || '8080');
  10. var data = {
  11. RPCClientClassName: rpcClientClassName,
  12. methods: [],
  13. port: port,
  14. host: req.host
  15. };
  16. for (method in remoteObj) {
  17. if (typeof(remoteObj[method]) === 'function') {
  18. data.methods.push({method_name: method});
  19. }
  20. }
  21. var helperTemplatePath = require('path').resolve(__dirname, 'helper.mustache');
  22. var jsContent = Mustache.render(fs.readFileSync(helperTemplatePath).toString(), data);
  23. res.end(jsContent);
  24. });
  25. rpcRouter.post('/:method', function (req, res) {
  26. var method = req.params.method;
  27. var args = JSON.parse(req.body.args);
  28. console.log('params:');
  29. console.log(req.body.args);
  30. if (remoteObj.hasOwnProperty(method) && typeof(remoteObj[method]) === 'function') {
  31. var fn = remoteObj[method];
  32. args.push(function (err, result) {
  33. var param = {
  34. err: err,
  35. data: result
  36. };
  37. res.set('Content-Type', 'application/json');
  38. var json = JSON.stringify(param);
  39. console.log('return:');
  40. console.log(json);
  41. res.send(200, json);
  42. });
  43. fn.apply({request: req}, args);
  44. } else {
  45. res.send(500);
  46. }
  47. });
  48. return rpcRouter;
  49. };