aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/dev/submelon/pantry/PantryItemController.java
blob: 142cbf6aa680d1dd83a2dd6bd8f5340cb3a95320 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package dev.submelon.pantry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(path="/items")
public class PantryItemController {
    @Autowired
    private PantryItemRepository itemRepository;

    @PostMapping(path="")
    @ResponseBody
    PantryItem addNewItem(@RequestBody PantryItem item) {
        return itemRepository.save(item);
    }

    @PutMapping(path="/{id}")
    @ResponseBody
    PantryItem addNewItem(@RequestBody PantryItem item, @PathVariable Long id) {
        return itemRepository.findById(id)
            .map(existingItem -> {
                existingItem.setName(item.getName());
                existingItem.setDescription(item.getDescription());
                existingItem.setQuantity(item.getQuantity());
                existingItem.setQuantityUnitType(item.getQuantityUnitType());
                return itemRepository.save(existingItem);
            })
            .orElseGet(() -> {
                return itemRepository.save(item);
            });
    }

    @GetMapping(path="")
    @ResponseBody
    Iterable<PantryItem> getAllItems() {
        return itemRepository.findAll();
    }
    
}