Конечная точка API, которая редактирует один элемент в списке - PullRequest
0 голосов
/ 05 апреля 2020

В настоящее время я создаю API для отдыха, который позволяет пользователю ввести рецепт и описать его. Я использую Spring-Boot в качестве бэкенда и angularjs в качестве внешнего интерфейса.

Это файл рецепта Springboot

package com.example.springboot;
import com.example.springboot.Recipe;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import  javax.validation.constraints.NotNull;

@Entity // This tells Hibernate to make a table out of this class

public class Recipe {

    public Recipe(){

    }

    public Recipe(Integer id, String name, String description, String type, Integer preptime, Integer cooktime, String content, Integer difficulty){
        this.id = id;
        this.name = name;
        this.description = description;
        this.type = type;
        this.preptime = preptimee;
        this.cooktime = cooktime;
        this.content = content;
        this.difficulty = difficulty;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;


    private String name;


    private String description;


    private String type;


    private Integer preptime;




    @Column(columnDefinition = "TEXT")
    private String content;

    private Integer difficulty;






    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Integer getDifficulty() {
        return difficulty;
    }

    public void setDifficulty(Integer difficulty) {
        this.difficulty = difficulty;
    }



    public Integer getpreptime {
        return preptime;
    }

    public void setpreptime(Integer preptime) {
        this.preptime = preptime;
    }
}

Я создал конечную точку, где пользователь может редактировать весь рецепт , Пользователь может редактировать имя, описание, содержимое и т. Д. В конечной точке recipes / edit / {id}. Конечная точка выглядит следующим образом.

@PutMapping("/recipes/edit/{id}")
    void updateRecipe(@PathVariable int id, @RequestBody Recipe recipe ) {
        System.out.println("entering");
        Recipe recipe_ = recipeRepository.findById(id).get();
        recipe_.setName(recipe.getName());
        recipe_.setDescription(recipe.getDescription());
        recipe_.setType(recipe.getType());
        recipe_.setpreptime(recipe.getpreptime());
        recipe_.setContent(recipe.getContent());


        System.out.println("entering " + recipe.getTitle());
        System.out.println("entering" + recipe.getType());
        System.out.println("entering" + recipe.getDescription());


        System.out.println("adding");
        recipeRepository.save(recipe_);
    }

Теперь я просто хочу создать конечную точку, которая служит только для переименования названия рецепта. Это отображение должно принимать список в качестве входных данных, а затем переименовывать только имя рецепта.

   @PutMapping("/recipes/rename")
      public List<Recipe> {
       System.out.println("entering renaming");
     //  recipe_.setName(recipe.getName()); ?


}

Я не знаю, как я могу это реализовать. Это то, что я придумал до сих пор. Конечная точка, которая принимает список в качестве параметра.

Это файл service.ts, который обновляет рецепты в функции редактирования service.ts:

updateRecipe (id: number, recipe: any): Observable<any > {
    const url = `${this.usersUrl}/edit/${id}`;
  return this.http.put(url ,recipe);
}

, где вызывается updateRecipe:

 save(): void {
    const id = +this.route.snapshot.paramMap.get('name');
     this.recipeService.updateRecipe2(id, this.recipes)
       .subscribe(() => this.gotoUserList());

   }

Эта реализация работает, я не знаю, как заставить ее работать или как я могу переписать функции так, чтобы она могла обновлять только имя рецепта, а не весь файл.

Может ли кто-нибудь мне помочь?

1 Ответ

0 голосов
/ 05 апреля 2020

Ваш update the name метод должен выглядеть следующим образом:

@PutMapping("...{id}")
public void updateName(@PathVariable Integer id, @RequestParam String name){
    Recipe recipe = repository.findById(id).orElseThrow(...);
    recipe.setName(name);
}

, если вы хотите переименовать список рецептов

public void renameRecipes(String oldName, String newName){
    repository.findByName(oldName)
              .forEach(r -> r.setName(newName));
}

@PutMapping("recipes/rename")
public void updateNames(@PequestParam String oldName, @RequestParam String newName){
    renameRecipes(oldName, newName);
}

Попробуйте это.

...