elastic-angular-client.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*! elastic.js - v1.0.0 - 2013-03-05
  2. * https://github.com/fullscale/elastic.js
  3. * Copyright (c) 2013 FullScale Labs, LLC; Licensed MIT */
  4. /*jshint browser:true */
  5. /*global angular:true */
  6. /*jshint es5:true */
  7. 'use strict';
  8. /*
  9. Angular.js service wrapping the elastic.js API. This module can simply
  10. be injected into your angular controllers.
  11. */
  12. angular.module('elasticjs.service', [])
  13. .factory('ejsResource', ['$http', function ($http) {
  14. return function (url) {
  15. var
  16. // use existing ejs object if it exists
  17. ejs = window.ejs || {},
  18. /* results are returned as a promise */
  19. promiseThen = function (httpPromise, successcb, errorcb) {
  20. return httpPromise.then(function (response) {
  21. (successcb || angular.noop)(response.data);
  22. return response.data;
  23. }, function (response) {
  24. (errorcb || angular.noop)(response.data);
  25. return response.data;
  26. });
  27. };
  28. // set url to empty string if it was not specified
  29. if (url == null) {
  30. url = '';
  31. }
  32. /* implement the elastic.js client interface for angular */
  33. ejs.client = {
  34. server: function (s) {
  35. if (s == null) {
  36. return url;
  37. }
  38. url = s;
  39. return this;
  40. },
  41. post: function (path, data, successcb, errorcb) {
  42. path = url + path;
  43. return promiseThen($http.post(path, data), successcb, errorcb);
  44. },
  45. get: function (path, data, successcb, errorcb) {
  46. path = url + path;
  47. return promiseThen($http.get(path, data), successcb, errorcb);
  48. },
  49. put: function (path, data, successcb, errorcb) {
  50. path = url + path;
  51. return promiseThen($http.put(path, data), successcb, errorcb);
  52. },
  53. del: function (path, data, successcb, errorcb) {
  54. path = url + path;
  55. return promiseThen($http.delete(path, data), successcb, errorcb);
  56. },
  57. head: function (path, data, successcb, errorcb) {
  58. path = url + path;
  59. return $http.head(path, data)
  60. .then(function (response) {
  61. (successcb || angular.noop)(response.headers());
  62. return response.headers();
  63. }, function (response) {
  64. (errorcb || angular.noop)(undefined);
  65. return undefined;
  66. });
  67. }
  68. };
  69. return ejs;
  70. };
  71. }]);