aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/dev/submelon/pantry/PantryItemController.java
blob: c1da12e97f28bd743ca242cd80d7d69508909d93 (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
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.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;

    @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();
    }
    
}