Food.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. (function() {
  2. // Basic api template all foods follow
  3. var abstractFood = function($resource, path) {
  4. var methods = {
  5. 'get': {
  6. url: "food/:id",
  7. method: 'GET'
  8. },
  9. 'query': {
  10. url: "food/"+path+"query/:query",
  11. method: 'GET',
  12. isArray: true
  13. },
  14. 'delete': {
  15. url: "food/:id",
  16. method: 'DELETE'
  17. }
  18. };
  19. if (path == "") {
  20. return $resource("food/"+path+':id', {id: "@id"}, methods);
  21. }
  22. else {
  23. // Create/Update requires you to know what type of food you're using
  24. methods.create = {method: 'PUT'};
  25. methods.update = {method: 'POST'};
  26. var res = $resource("food/"+path+':id', {id: "@id"}, methods);
  27. // TODO: Pass arguments generically
  28. res.prototype.$save = function(success, failure) {
  29. if (!this.id) {
  30. return this.$create(success, failure);
  31. }
  32. else {
  33. return this.$update(success, failure);
  34. }
  35. };
  36. return res;
  37. }
  38. };
  39. angular.module('Food', ['ngResource'])
  40. .factory('BasicFood', ['$resource', function($resource) {
  41. var res = abstractFood($resource, 'basic/');
  42. res.fromNdb = function(ndbItem) {
  43. return new this({
  44. ndbno: parseInt(ndbItem.ndbno),
  45. name: ndbItem.name,
  46. food_group: ndbItem.fg,
  47. default_unit: ndbItem.ru,
  48. calories_p_100: ndbItem.nutrients.find(function (nutrient) {
  49. // TODO: Replace 208 with soft-loaded value from database
  50. // 208 is the id for kCalories
  51. return nutrient.nutrient_id == 208;
  52. }).value
  53. });
  54. };
  55. return res;
  56. }])
  57. .factory('Recipe', ['$resource', function($resource) {
  58. return abstractFood($resource, 'recipe/');
  59. }])
  60. .factory('Food', ['$resource', 'BasicFood', 'Recipe', function($resource, BasicFood, Recipe) {
  61. var absFood = abstractFood($resource, "");
  62. absFood.prototype.cast = function() {
  63. switch (this.type) {
  64. case "BasicFood":
  65. return new BasicFood(this);
  66. case "Recipe":
  67. return new Recipe(this);
  68. default:
  69. throw "Unrecognized food type: "+this.type;
  70. }
  71. };
  72. return absFood;
  73. }]);
  74. })();