Kaynağa Gözat

Handle error messages in Scrape endpoint. TG-11 #in-progress

Tati 7 yıl önce
ebeveyn
işleme
57c5fe916d

+ 1 - 0
ktchn/src/recipes/model.ts

@@ -48,6 +48,7 @@ export interface Recipe {
   details?: RecipeDetails;
   instructions?: string[];
   author?: Author;
+  website?: string;
   tags?: string[];
   course?: string[];
   summary?: string;

+ 6 - 1
ktchn/src/recipes/routes.ts

@@ -17,7 +17,12 @@ class RecipeRoutes {
     this.router.post("/scrape", (req, res, next) => {
        return Scrape(req.body.url).then((x)=>{
          res.json(x)
-       });
+       }).catch((error: Error) => res.status(400).send(
+        {
+          name: error.name,
+          message: error.message,
+        }
+      ));
     })
   }
 }

+ 17 - 5
ktchn/src/recipes/scrape/index.ts

@@ -6,9 +6,20 @@ import { Ingredient } from '../model';
 import { parse as parseIngredient } from 'recipe-ingredient-parser';
 
 function selectSource(url: string): ScrapingSource|void {
-  return Sources.find((source) => {
+  return ;
+}
+
+function selectSourceAsync(url: string): Promise<ScrapingSource> {
+  const foundSource = Sources.find((source) => {
     return url.search(source.domain) > 0;
   });
+  return new Promise((resolve, reject) => {
+    if (foundSource) {
+      return resolve(foundSource);
+    } else {
+      reject(new Error('Source not found'))
+    }
+  });
 }
 
 export const parseIngredients = (rawIngredient: string): Ingredient => {
@@ -28,10 +39,11 @@ async function scrape(url:string) {
       normalizeWhitespace: true
     }),
   };
-  const $ = await RequestPromise(options);
-  let source = selectSource(url);
-  return source ? source.scrapeRecipe($) : new Error('source not found');
-
+  return RequestPromise(options).then(
+    $ => selectSourceAsync(url).then(
+      source => source.scrapeRecipe($)
+    )
+  )
 }
 
 export default scrape;