server.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. module.exports = function apiServer (getApi) {
  2. apiCall.getApi = getApi;
  3. apiCall.delimiter = '/';
  4. return apiCall;
  5. function apiCall (path, args) {
  6. return new Promise(function (win, fail) {
  7. try {
  8. var api = apiCall.getApi();
  9. } catch (e) {
  10. fail("api: error getting api: " + e.message)
  11. }
  12. try {
  13. var split = (isFunction(apiCall.delimiter)
  14. ? apiCall.delimiter(path)
  15. : path.split(apiCall.delimiter))
  16. } catch (e) {
  17. fail("api: error parsing path " + path + ": " + e.message)
  18. }
  19. resolve(api, split);
  20. function resolve (branch, steps) {
  21. if (steps.length < 1) {
  22. fail("api: no path specified")
  23. return;
  24. }
  25. if (steps.length > 1) {
  26. descend(branch, steps)
  27. return;
  28. }
  29. var method = branch[steps[0]];
  30. if (method === undefined) {
  31. fail("api: " + path + " not found")
  32. }
  33. if (!isFunction(method)) {
  34. fail("api: " + path + " not a function but " + typeof method)
  35. }
  36. win(method.apply(branch, args));
  37. }
  38. function descend (branch, steps) {
  39. if (!exists(branch, steps[0])) {
  40. fail("api: " + path + " is not in the api" +
  41. " (starting from '" + steps[0] + "')")
  42. return;
  43. }
  44. var next = branch[steps[0]];
  45. if (!isFunction(next)) {
  46. resolve(next, steps.slice(1))
  47. } else {
  48. next = next();
  49. if (!isPromise(next)) {
  50. resolve(next, steps.slice(1))
  51. } else {
  52. next.then(function (val) {
  53. resolve(val, steps.slice(1))
  54. })
  55. }
  56. }
  57. }
  58. })
  59. }
  60. }
  61. function exists (branch, name) {
  62. return Object.keys(branch).indexOf(name) > -1
  63. }
  64. function isFunction (x) {
  65. return typeof x === "function"
  66. }
  67. function isObject(x) {
  68. return x === Object(x)
  69. }
  70. function isPromise(x) {
  71. return isObject(x) && isFunction(x.then)
  72. }