controller.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import { Request, Response, NextFunction } from 'express'
  2. import { Recipe, IIngredient, IngredientSuggestion, RecipeDB } from './model';
  3. import { IMongoService } from '../mongo';
  4. import { FilterQuery, ObjectID } from 'mongodb';
  5. import Scrape from './scrape/index';
  6. import { ScrapedRecipe } from './model';
  7. import Ingredient from '../ingredients/model';
  8. import { dissoc } from 'ramda';
  9. import request from 'request-promise';
  10. import fs from 'fs';
  11. function validRecipe(data: any): Promise<Recipe> {
  12. return new Promise(function(resolve, reject) {
  13. return data.name !== undefined ? resolve(data) : reject('Missing data');
  14. })
  15. }
  16. type Controller = (db: IMongoService) => (req: Request, res: Response, next: NextFunction) => Promise<void|Response>;
  17. type ChainPController<T, U> = (req: Request, res: Response, next: NextFunction) => (result: T) => Promise<U>;
  18. const getSuggestions = (db: IMongoService) => async function(ingredient: IIngredient): Promise<IngredientSuggestion> {
  19. // @ts-ignore: yes
  20. const suggestions = await db.find<Ingredient>({$text: {$search: ingredient.name}}, { score: { $meta: "textScore" } });
  21. return {
  22. ...ingredient,
  23. suggestions,
  24. }
  25. }
  26. async function getImage(src?: string): Promise<string> {
  27. if (src) {
  28. try {
  29. const result = await request({ uri: src, resolveWithFullResponse: true, encoding: null });
  30. const data = "data:" + result.headers["content-type"] + ";base64," + new Buffer(result.body).toString('base64');
  31. return data;
  32. } catch (e) {
  33. return ''
  34. }
  35. }
  36. return Promise.resolve('')
  37. }
  38. const scrapeRecipe: (db: IMongoService) => ChainPController<void, ScrapedRecipe> = (db) => (req) => () => {
  39. return Scrape(req.body.url)
  40. .then(async scrapedRecipe => {
  41. const recipeIngredients = await Promise.all(scrapedRecipe.ingredients.map(async subGroup => {
  42. const subgroupIngredients = await Promise.all(subGroup.ingredients.map(getSuggestions(db)));
  43. return ({
  44. name: subGroup.name,
  45. ingredients: subgroupIngredients
  46. });
  47. }));
  48. const image = await getImage(scrapedRecipe.image);
  49. return {
  50. ...scrapedRecipe,
  51. ingredients: recipeIngredients,
  52. image,
  53. }
  54. })
  55. }
  56. const saveImage = async (recipe: Recipe, _id: ObjectID) => {
  57. if (recipe.image) {
  58. try {
  59. const [ prefix, base64Img ] = recipe.image.split(',');
  60. const filename = `${_id}.${prefix.replace('data:image/', '').split(';', 1)}`;
  61. fs.writeFileSync(`${__dirname}/../public/${filename}`, base64Img, { encoding: 'base64'});
  62. return {
  63. ...recipe,
  64. image: filename
  65. }
  66. } catch (e) {
  67. throw Error(e);
  68. }
  69. } else {
  70. return recipe;
  71. }
  72. }
  73. const deleteRecipe: Controller = (db) => ({ params }, res) => {
  74. return db.deleteMany<Recipe>({_id: new ObjectID(params.id)})
  75. .then(result => res.json(result.result))
  76. }
  77. const save: Controller = (db) => ({ body }, res) => {
  78. const _id = new ObjectID();
  79. return validRecipe(body)
  80. .then(recipe => saveImage(recipe, _id))
  81. .then(recipe => db.insertOne({ ...recipe, _id }))
  82. .then(dbrecipe => res.json(dbrecipe));
  83. };
  84. const get: Controller = (db) => ({ query }, res) => {
  85. return db.findOne<Recipe>(query).then(result => res.json(result));
  86. }
  87. const getById: Controller = (db) => ({ params }, res) => {
  88. return db.findOneById<Recipe>(params.id).then(recipe => res.json(recipe));
  89. }
  90. const getAll: Controller = (db) => ({ query }, res) => {
  91. const _query = Object.keys(query).reduce((q, field) => {
  92. return {
  93. ...q,
  94. ...buildSearchQuery(field, query[field])
  95. }
  96. }, {});
  97. return db.find<Recipe>(_query).then(recipes => res.json(recipes));
  98. }
  99. type RegexQuery = {
  100. '$regex': string,
  101. '$options': 'i'
  102. };
  103. const buildSearchQuery = (fieldName: string, value: string): { [field: string] : RegexQuery} => ({
  104. [fieldName]: {
  105. '$regex': value,
  106. '$options': 'i'
  107. }
  108. });
  109. async function buildQuery(tryQuery:()=>FilterQuery<any>): Promise<FilterQuery<any>> {
  110. try {
  111. return Promise.resolve(tryQuery());
  112. } catch(error) {
  113. return Promise.reject(error);
  114. }
  115. }
  116. const getByIngredients: Controller = (db) => ({ query }, res) => {
  117. const ingredientsQuery = (query: FilterQuery<any>) => () => {
  118. if(query.ingredients) {
  119. const ingredients: string[] = query.ingredients.split(',');
  120. return {
  121. '$or': ingredients.map((ing) => buildSearchQuery('ingredients.ingredients.name', ing))
  122. };
  123. } else {
  124. throw new Error('Invalid query key');
  125. }
  126. }
  127. return buildQuery(ingredientsQuery(query)).then(
  128. builtQuery => db.find<Recipe>(builtQuery).then(
  129. recipes => res.json(recipes)
  130. )
  131. )
  132. }
  133. const updateOriginal = (ingredient: IIngredient): string => (`
  134. ${ingredient.quantity} ${ingredient.unit||''} ${ingredient.unit && 'of'} ${ingredient.name}
  135. `);
  136. const update: Controller = (db) => ({params, body}, res) => {
  137. let newRecipe = dissoc('_id', body) as Recipe;
  138. newRecipe.ingredients = newRecipe.ingredients.map(subRecipe => ({
  139. ...subRecipe,
  140. ingredients: subRecipe.ingredients.map(ingredient => ({
  141. ...ingredient,
  142. _original: updateOriginal(ingredient)
  143. }))
  144. }));
  145. return saveImage(newRecipe, new ObjectID(params.id)).then(
  146. recipe => db.update<Recipe>(params.id, recipe).then(
  147. result => res.json(result))
  148. )
  149. }
  150. export {
  151. save,
  152. scrapeRecipe,
  153. getById,
  154. get,
  155. getAll,
  156. getByIngredients,
  157. update,
  158. deleteRecipe
  159. }