Skip to content

Commit

Permalink
add recipe done
Browse files Browse the repository at this point in the history
  • Loading branch information
lordkener committed Apr 16, 2020
1 parent 01331ff commit 40a468e
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -125,7 +126,7 @@ public ResponseEntity<RecipeDTO> postRecipe(@RequestBody RecipeDTO recipeDTO) th
Recipe r = indexService.postRecipe(userSession.getLoggedUser(),recipe, ingredientsString, categoriesString,
cookingStyle, recipeDTO.getAllergen(), recipeDTO.getFirstStep(), stepsString, withImage, null, null);
if (r != null) {
return new ResponseEntity<>(recipeDTO, HttpStatus.OK);
return new ResponseEntity<>(recipeDTO, HttpStatus.CREATED);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Expand All @@ -136,14 +137,13 @@ public ResponseEntity<RecipeDTO> postRecipe(@RequestBody RecipeDTO recipeDTO) th
}

// POST AN IMAGE OF ONE STEP OF ONE RECIPE
@JsonView(IndexRestController.PostRecipe.class)
@PostMapping(value = "/index/{id}/image/{step}", produces = MediaType.IMAGE_JPEG_VALUE)
@PostMapping(value = "/index/{id}/image/{step}")
public ResponseEntity<byte[]> postRecipeImage(@PathVariable Long id, @PathVariable int step,
@RequestParam MultipartFile imageFile)throws IOException {
if(userSession.isLoggedUser()){
byte[] image = indexService.postRecipeImages(userSession.getLoggedUser(), id, step, imageFile);
if(image != null){
return new ResponseEntity<>(image, HttpStatus.OK);
return new ResponseEntity<>(image, HttpStatus.CREATED);
}else{
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ public interface Main extends User.Username, Recipe.RecipeBasic, Recipe.RecipePl
@Autowired
private UsersRepository usersRepository;

@GetMapping("/last")
public ResponseEntity<Integer> getLastRecipeId() {
Integer allRecipes = recipesRepository.findAll().size();
return new ResponseEntity<>(allRecipes, HttpStatus.OK);
}

// AJAX PAGEABLE RECIPES
@JsonView(RecipeRestController.Main.class)
@GetMapping("/")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,11 @@ public Recipe postRecipe(User user, Recipe recipe, String ingredientsString, Str
if(steps != null){
Step step_n = new Step(recipe, i, steps);
if(listOfBools.get(j).equalsIgnoreCase("1")){
imageService.saveImage("recipes/steps/"+recipe.getId(), j+2, allImages[j]);
step_n.setImage(true);
step_n.setStepImage(allImages[j].getBytes());
if(allImages != null){
imageService.saveImage("recipes/steps/"+recipe.getId(), j+2, allImages[j]);
step_n.setImage(true);
step_n.setStepImage(allImages[j].getBytes());
}
}else{
step_n.setImage(false);
}
Expand Down
2 changes: 1 addition & 1 deletion frontend/instarecipes/src/app/index/index.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@

<!-- Buttons Add, Search and Ajax -->
<popup-filter></popup-filter>
<popup-add *ngIf="authService.isLogged"></popup-add>
<popup-add></popup-add>
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ <h3 class="underlined-text">Aproximated time</h3>
</div>
</div>
<button id="post-recipe" type='submit' class="btn btn-primary" style="margin-top: 20px; height: 50px;width: 10%;">Post</button>
<button type="button" #closebutton class="close" data-dismiss="modal" hidden></button>
</form>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {Component, OnInit, ViewChild, ElementRef} from '@angular/core';
import { NgForm } from '@angular/forms';
import { CookingStyle } from 'src/app/Interfaces/cookingStyle.model';
import { ProfileService } from 'src/app/services/profile.service';
import { Ingredient } from 'src/app/Interfaces/ingredient.model';
Expand All @@ -8,7 +7,6 @@ import { Allergen } from 'src/app/Interfaces/allergen.model';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { RecipeDTO } from 'src/app/Interfaces/recipeDTO.model.js';
import { RecipesService } from 'src/app/services/recipes.service.js';
import { Router } from '@angular/router';
import { Step } from 'src/app/Interfaces/step.model.js';

@Component({
Expand Down Expand Up @@ -37,6 +35,8 @@ export class AddRecipeComponent implements OnInit{
@ViewChild('otherImages') otherImages: ElementRef;
@ViewChild('mainImage') mainImage: ElementRef;

@ViewChild('closebutton') closebutton: ElementRef;

firstStepAux: string = '';
allergenAux: string = '';
withImageAux: string[] = [];
Expand Down Expand Up @@ -139,30 +139,40 @@ export class AddRecipeComponent implements OnInit{
this.recipe.withImage.push(this.otherImages.nativeElement.value);
console.log(this.recipe);
console.log(this.fileToUpload);
let totalRecipes = [];
this.recipeService.postRecipe(this.recipe).subscribe(
_ => {
this.recipeService.refreshRecipes(100).subscribe(
recipes => {
totalRecipes = recipes;
console.log("Tamanio: " + totalRecipes.length);
this.recipeService.postImageStep(this.fileToUpload, totalRecipes.length+2, 1).subscribe(
imagen => {
console.log("Imagen subida" + imagen);
this.stepsFiles.forEach((value, key) => {
this.recipeService.postImageStep(value, totalRecipes.length+2, key).subscribe(
file => {
console.log("Imagen del paso " + key + " subida exitosamente: " + file);
})
});
this.initConstructor();
_ =>{
console.log("Posted recipe: "+JSON.stringify(_));
this.recipeService.getLastRecipeId().subscribe(
lastId => {
console.log("Last id: " + lastId);
this.recipeService.postImageStep(this.fileToUpload, lastId, 1).subscribe(
_ => { },
error => {
console.log("Tamanio de stepsFiles: " + this.stepsFiles.size);
if(this.stepsFiles.size<1){
this.initConstructor();
this.closebutton.nativeElement.click();
}else{
this.stepsFiles.forEach((value, key) => {
this.recipeService.postImageStep(value, lastId, key).subscribe(
what=> console.log("Imagen del paso " + key + " subida exitosamente: " + value.name),
error3 => {
console.error('Error creating others recipe steps images');
if(key === this.stepsFiles.size){
this.initConstructor();
this.closebutton.nativeElement.click();
this.mainImage.nativeElement.setAttribute("src","");
}
}
)});
}
},
(error: Error) => console.error('Error creating recipe step image: ' + error),
);
}
},
error => {console.log("Error getting last id of recipe")}
);
},
(error: Error) => console.error('Error creating new recipe: ' + error),
error => {console.log("Error posting a recipe")}
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class RecentComponent implements OnInit{
private domSanitizer: DomSanitizer){ }

ngOnInit(){
this.refresh(this.page_size);
setInterval(()=> { this.refresh(this.page_size) }, 10 * 1000); //cada 10 segundos se actualiza
}

refresh(pS: number) {
Expand Down
32 changes: 18 additions & 14 deletions frontend/instarecipes/src/app/services/recipes.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Recipe } from '../Interfaces/recipe.model';
import { catchError } from 'rxjs/operators';
import { catchError, map, retry, tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { Step } from '../Interfaces/step.model';
import { RecipeDTO } from '../Interfaces/recipeDTO.model';
import { throwError } from 'rxjs';

const BASE_URL: string = "/api/recipes/";

Expand All @@ -25,6 +26,12 @@ export class RecipesService {
) as Observable<Recipe[]>;
}

getLastRecipeId(): Observable<number>{
return this.httpClient.get(BASE_URL + "last").pipe(
catchError(error => this.handleError(error))
) as Observable<number>;
}

getRecipeAvatar(id_user: number): Observable<Blob> {
let head = new HttpHeaders();
head = head.set('Content-Type', 'image/jpeg');
Expand Down Expand Up @@ -53,6 +60,7 @@ export class RecipesService {
catchError(error => this.handleError(error))
) as Observable<Recipe>;
}

getSteps(id_recipe: number): Observable<Step[]>{
return this.httpClient.get(BASE_URL + id_recipe + '/steps').pipe(
catchError(error => this.handleError(error))
Expand All @@ -65,30 +73,26 @@ export class RecipesService {
) as Observable<Recipe[]>;
}

postRecipe(recipe: RecipeDTO): Observable<RecipeDTO> {
postRecipe(recipe: RecipeDTO) {
const body = JSON.stringify(recipe);
const headers = new HttpHeaders({
'Content-Type': 'application/json',
});
return this.httpClient.post<RecipeDTO>("/api/index", body, { headers }).pipe(
catchError(
error => this.handleError(error)
)
) as Observable<RecipeDTO>;
catchError(error => this.handleError(error))
);
}

postImageStep(imageFile: File, recipe_id: number, step: number): Observable<boolean> {
postImageStep(imageFile: File, recipe_id: number, step: number): Observable<any[]> {
let data: FormData = new FormData();
data.append('imageFile', imageFile, imageFile.name);
return this.httpClient.post("/api/index/"+recipe_id+"/image/"+step, data).pipe(
catchError(
error => this.handleError(error)
)
) as Observable<boolean>;
data.append('imageFile', imageFile);
return this.httpClient.post<any>("/api/index/"+recipe_id+"/image/"+step, data).pipe(
catchError(error => this.handleError(error))
) as Observable<any[]>;
}

private handleError(error: any) {
console.error(error);
return Observable.throw("Server error (" + error.status + '): ' + error.text());
return Observable.throw("Server error (" + error.status + "): " + error.text())
}
}

0 comments on commit 40a468e

Please sign in to comment.