units.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * Provides interface for unit apis.
  3. */
  4. (function() {
  5. var restResource = function($resource) {
  6. return function() {
  7. arguments[2]["create"] = {
  8. method: "PUT"
  9. };
  10. arguments[2]["update"] = {
  11. method: "POST"
  12. };
  13. var res = $resource.apply(null, arguments);
  14. res.prototype.$save = function() {
  15. return this[this.id? "$update":"$create"].apply(this, arguments);
  16. };
  17. return res;
  18. };
  19. };
  20. function normalizeFromMass(amountG, food) {
  21. switch (food.unit_type) {
  22. case "volume":
  23. return amountG / food.density;
  24. case "count":
  25. throw "Not yet implemented!";
  26. //return amountG / food.mass_p_unit;
  27. }
  28. }
  29. function normalizeFromVolume(amountMl, food) {
  30. switch (food.unit_type) {
  31. case "mass":
  32. return amountMl * food.density;
  33. case "count":
  34. throw "Not yet implemented!";
  35. //return amountMl * food.density / food.mass_p_unit;
  36. }
  37. }
  38. function normalizeFromCount(amountUnit, food) {
  39. switch (food.unit_type) {
  40. case "mass":
  41. throw "Not yet implemented!";
  42. //return amountUnit * food.mass_p_unit;
  43. case "volume":
  44. throw "Not yet implemented!";
  45. //return amountUnit * food.mass_p_unit / food.density;
  46. }
  47. }
  48. angular.module('Units', ['ngResource'])
  49. /*
  50. * Collection of unit apis.
  51. *
  52. * Methods:
  53. * get: Gets information for a unit by id
  54. * query: Get a list of all units
  55. * queryType: Get a list of all units of a type
  56. * delete: Deletes a unit with an id
  57. * create: Creates a unit
  58. * update: Updates a unit
  59. * normalize: Converts from the given unit amount to the primary unit
  60. * save: Creates a new unit or updates an existing unit
  61. */
  62. .factory('Unit', ['$resource', function($resource) {
  63. var res = restResource($resource)("unit/:id", {id: "@id"}, {
  64. "queryType": {
  65. method: 'GET',
  66. isArray: true,
  67. url: "unit/type/:type"
  68. },
  69. "primary": {
  70. method: 'GET',
  71. isArray: true,
  72. url: "unit/primary/:type"
  73. }
  74. });
  75. res.prototype.normalize = function(food, amount) {
  76. var normalizedToType = amount * this.conversion;
  77. if (food.unit_type == this.type) {
  78. return normalizedToType;
  79. }
  80. else {
  81. switch (this.type) {
  82. case "mass":
  83. return normalizeFromMass(normalizedToType, food);
  84. case "volume":
  85. return normalizeFromVolume(normalizedToType, food);
  86. case "count":
  87. return normalizeFromCount(normalizedToType, food);
  88. }
  89. }
  90. };
  91. return res;
  92. }]);
  93. })();