فهرست منبع

Create promise all middleware. Use it in recipe routes

Tati 7 سال پیش
والد
کامیت
b7cdce3da7
5فایلهای تغییر یافته به همراه37 افزوده شده و 43 حذف شده
  1. 5 4
      ktchn/src/mongo.ts
  2. 16 0
      ktchn/src/promise-all-middleware.ts
  3. 12 10
      ktchn/src/recipes/controller.ts
  4. 0 22
      ktchn/src/recipes/data.ts
  5. 4 7
      ktchn/src/recipes/routes.ts

+ 5 - 4
ktchn/src/mongo.ts

@@ -1,18 +1,19 @@
-import { Db, connect, MongoClient, InsertOneWriteOpResult, Collection, ObjectID } from 'mongodb';
+import { Db, connect, MongoClient, InsertOneWriteOpResult, Collection, ObjectID, FilterQuery } from 'mongodb';
 
-export interface IDBObject<T extends {}> {
+export interface IDBDocument<T extends {}> {
   _id: ObjectID
 }
 
 export interface IMongoService {
-  insertOne<T>(data: T): Promise<IDBObject<T>>,
+  insertOne<T>(data: T): Promise<IDBDocument<T>>,
 }
 
 export const mongoService = (db: Db) => (col: string) => {
   const collection:Collection = db.collection(col);
 
   return {
-    insertOne: <T>(data: T): Promise<IDBObject<T>> => collection.insertOne(data).then(insertOneResult => insertOneResult.ops[0])
+    insertOne: <T>(data: T): Promise<IDBDocument<T>> => collection.insertOne(data).then(insertOneResult => insertOneResult.ops[0]),
+    findOne: <T>(query: FilterQuery<T>) => collection.findOne(query),
   }
 };
 

+ 16 - 0
ktchn/src/promise-all-middleware.ts

@@ -0,0 +1,16 @@
+import { Request, NextFunction, Response } from 'express';
+import { promises } from 'fs';
+
+export interface IMiddleware {
+  (req: Request, res: Response, next: NextFunction): Promise<any>
+}
+
+const piddleware = (middlewares: IMiddleware[]) => (req: Request, res: Response, next: NextFunction): void => {
+  middlewares.reduce((middlewaresChain, currentMiddleware) => {
+    return middlewaresChain.then(x => currentMiddleware(req, res, next))
+  }, Promise.resolve([])).then(results => { // results would be ever necessary ?  
+    next();
+  }).catch(error => next(error));
+}
+
+export default piddleware;

+ 12 - 10
ktchn/src/recipes/controller.ts

@@ -6,17 +6,19 @@ function isValidRecipe(data: any): data is Recipe {
   return data.name !== undefined;
 }
 
-const saveRecipe = (db: IMongoService) => ({ body }: Request, res: Response, next: NextFunction): void => {
-  if (isValidRecipe(body)) {
-    db.insertOne(body).then(DBRecipe => {
-      res.json(DBRecipe);
-      next();
-    }).catch(error => { next(error) })
-  } else {
-    next(new Error('Missing recipe information'));
-  }
+function validRecipe(data: any): Promise<Recipe> {
+  return new Promise(function(resolve, reject) {
+    return data.name !== undefined ? resolve(data) : reject('Missing data');
+  })
 }
 
+const save = (db: IMongoService) => ({ body }: Request, res: Response, next: NextFunction): Promise<any> => {
+  return validRecipe(body).then(
+    recipe => db.insertOne(recipe).then(
+      dbRecipe => res.json(dbRecipe)
+  ));
+};
+
 export {
-  saveRecipe,
+  save,
 }

+ 0 - 22
ktchn/src/recipes/data.ts

@@ -1,22 +0,0 @@
-import { Recipe, RecipeDB } from './model';
-import { Request, Response, NextFunction } from 'express'
-import MongoClient from 'mongodb';
-import mongo from './../mongo';
-
-function storeRecipe(db: MongoClient.Db) {
-  return async function (req: Request, res: Response, next: NextFunction) {
-    try {
-      const data = await db.collection('recipes').insertOne(res.locals.data);
-      res.locals.savedData = data.ops[0] as RecipeDB;
-      res.json(data.ops[0]);
-      next();
-    }
-    catch (error) {
-      return next(error);
-    }
-  } 
-}
-
-export {
-  storeRecipe,
-}

+ 4 - 7
ktchn/src/recipes/routes.ts

@@ -1,9 +1,10 @@
 import { Request, Response, Router, NextFunction } from "express";
 import Scrape from "./scrape";
 import { Recipe } from './model';
-import { saveRecipe } from './controller';
+import { save } from './controller';
 import MongoClient from 'mongodb';
 import { mongoService, IMongoService } from '../mongo';
+import piddleware from '../promise-all-middleware';
 
 class RecipeRoutes {
   public router: Router;
@@ -16,12 +17,8 @@ class RecipeRoutes {
   }
 
   private init() {
-    this.router.get("/", (req, res, next) => {
-      res.json({
-        message: 'hey recipes bb'
-      });
-    })
-    this.router.post("/", saveRecipe(this.RecipeDB))
+    // this.router.get("/", (req, res, next) => )
+    this.router.post('/', piddleware([save(this.RecipeDB)]))
     this.router.post("/scrape", (req, res, next) => {
        return Scrape(req.body.url).then((x)=>{
          res.json(x)