in progress: associate ingredients to recipe on save

This commit is contained in:
Mikayla Dobson
2023-02-19 12:04:46 -06:00
parent 47360518ce
commit 63d0049450
8 changed files with 116 additions and 15 deletions

View File

@@ -1,4 +1,4 @@
import { IRecipe } from "../schemas";
import { IRecipe, RecipeIngredient } from "../schemas";
import { Recipe } from "../models/recipe";
import ControllerResponse from "../util/ControllerResponse";
import { StatusCode } from "../util/types";
@@ -58,4 +58,15 @@ export default class RecipeCtl {
throw new Error(error);
}
}
async addIngredientToRecipe(ingredient: RecipeIngredient, recipeid: string | number) {
try {
const result = await RecipeInstance.addIngredientToRecipe(ingredient, recipeid);
const ok = result !== null;
const code = ok ? StatusCode.NewContent : StatusCode.BadRequest;
return new ControllerResponse(code, (result || "Something went wrong"));
} catch (error: any) {
throw new Error(error);
}
}
}

View File

@@ -1,4 +1,4 @@
import { IRecipe } from "../schemas";
import { IIngredient, IRecipe, RecipeIngredient } from "../schemas";
import fs from 'fs';
import pool from "../db";
import { CollectionCtl } from "../controllers";
@@ -114,4 +114,24 @@ export class Recipe {
throw new Error(error);
}
}
async addIngredientToRecipe(ingredient: RecipeIngredient, recipeid: string | number) {
const { quantity, unit, id } = ingredient;
try {
const statement = `
INSERT INTO recipin.cmp_recipeingredient
(quantity, unit, ingredientid, recipeid)
VALUES ($1, $2, $3, $4) RETURNING *
`
const result = await pool.query(statement, [quantity, unit, id, recipeid]);
if (result.rows) return result.rows[0];
return [];
} catch (e: any) {
throw new Error(e);
}
}
}

View File

@@ -51,4 +51,6 @@ export const ingredientRoute = (app: Express) => {
next(e);
}
})
return router;
}

View File

@@ -57,10 +57,16 @@ export const recipeRoute = (app: Express) => {
router.post('/', restrictAccess, async (req, res, next) => {
const user = req.user as IUser;
const data = req.body;
const { addIngredients, recipeID } = req.query;
try {
const result = await recipectl.post(user.id as number, data);
res.status(result.code).send(result.data);
if (addIngredients) {
const result = await recipectl.addIngredientToRecipe(data, recipeID as string);
res.status(result.code).send(result.data);
} else {
const result = await recipectl.post(user.id as number, data);
res.status(result.code).send(result.data);
}
} catch(e) {
next(e);
}

View File

@@ -44,6 +44,11 @@ export interface IIngredient extends HasHistory {
createdbyid: string | number
}
export interface RecipeIngredient extends Partial<IIngredient> {
unit: string
quantity: string | number
}
export interface ICollection extends HasHistory, CanDeactivate {
name: string
ismaincollection: boolean