added incomplete recipe point, controller and mapper implementation
This commit is contained in:
parent
d94251dea4
commit
3a887d8dbb
5 changed files with 134 additions and 2 deletions
76
src/controllers/RecipeController.ts
Normal file
76
src/controllers/RecipeController.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { Entity } from "typeorm";
|
||||
import { RecipeDto } from "../dtos/RecipeDto.js";
|
||||
import { RecipeDtoEntityMapper } from "../mappers/RecipeDtoEntityMapper.js";
|
||||
import { RecipeRepository } from "../repositories/RecipeRepository.js";
|
||||
import { RecipeEntity } from "../entities/RecipeEntity.js";
|
||||
import { ValidationError } from "../errors/httpErrors.js";
|
||||
import { RecipeInstructionStepDto } from "../dtos/RecipeInstructionStepDto.js";
|
||||
|
||||
/**
|
||||
* Controls all user specific actions
|
||||
*/
|
||||
export class RecipeController {
|
||||
constructor(
|
||||
private repository: RecipeRepository,
|
||||
private mapper: RecipeDtoEntityMapper
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Load list of all recipes
|
||||
* @returns List of all recipes
|
||||
*/
|
||||
async getAllRecipes(){
|
||||
const recipeEntities = await this.repository.findAll();
|
||||
let recipeDtos : RecipeDto[] = [];
|
||||
recipeEntities.forEach(recipeEntity => {
|
||||
recipeDtos.push(this.mapper.toDto(recipeEntity));
|
||||
});
|
||||
return recipeDtos;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new recipe
|
||||
* @param dto RecipeDto containing the new recipe
|
||||
*/
|
||||
async createRecipe(dto : RecipeDto){
|
||||
if(!this.isRecipeDtoValid(dto)){
|
||||
throw new ValidationError("recipe data is not valid!")
|
||||
}
|
||||
const recipeEntity = this.mapper.toEntity(dto)
|
||||
const entity = await this.repository.create(recipeEntity);
|
||||
return this.mapper.toDto(entity);
|
||||
}
|
||||
|
||||
protected isRecipeDtoValid(dto :RecipeDto) : boolean {
|
||||
let isValid = true;
|
||||
if(dto.title == undefined
|
||||
|| dto.title.length == 0
|
||||
|| dto.amount == undefined
|
||||
|| dto.amountDescription == undefined
|
||||
|| dto.amountDescription.length == 0
|
||||
|| !this.isInstructionsValid(dto.instructions)
|
||||
){
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
// @todo ingredient groups
|
||||
|
||||
return isValid;
|
||||
}
|
||||
protected isInstructionsValid(instructions: RecipeInstructionStepDto[]|undefined) : boolean {
|
||||
if(instructions == undefined || instructions.length == 0){
|
||||
return false;
|
||||
}
|
||||
let isValid = true;
|
||||
instructions.forEach(step =>{
|
||||
if(step.text == undefined
|
||||
|| step.text.length == 0
|
||||
|| step.sortOrder == undefined
|
||||
){
|
||||
isValid = false;
|
||||
}
|
||||
});
|
||||
|
||||
return isValid;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue