elastic-angular-client.js 2.3 KB

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