controller.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { Request, Response, NextFunction } from 'express'
  2. import { Recipe } from './model';
  3. import { IMongoService } from '../mongo';
  4. import { ObjectId } from 'bson';
  5. import { json } from 'body-parser';
  6. function validRecipe(data: any): Promise<Recipe> {
  7. return new Promise(function(resolve, reject) {
  8. return data.name !== undefined ? resolve(data) : reject('Missing data');
  9. })
  10. }
  11. const save = (db: IMongoService) => ({ body }: Request, res: Response, next: NextFunction): Promise<any> => {
  12. return validRecipe(body).then(
  13. recipe => db.insertOne(recipe).then(
  14. dbRecipe => res.json(dbRecipe)
  15. ));
  16. };
  17. const get = (db: IMongoService) => ({ query }: Request, res: Response, next: NextFunction) => {
  18. return db.findOne<Recipe>(query).then(result => res.json(result));
  19. }
  20. const getById = (db: IMongoService) => ({ params }: Request, res: Response, next: NextFunction) => {
  21. return db.findOneById<Recipe>(params.id).then(recipe => res.json(recipe));
  22. }
  23. const getAll = (db: IMongoService) => ({ query }: Request, res: Response, next: NextFunction) => {
  24. return db.find<Recipe>(query).then(recipes => res.json(recipes));
  25. }
  26. export {
  27. save,
  28. getById,
  29. get,
  30. getAll,
  31. }