aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/dev/submelon/rest/json/PantryItemResource.java
blob: 4bb51c00760d2237b4de5e5820900768100018f5 (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
48
49
50
51
52
53
54
55
56
57
58
59
package dev.submelon.rest.json;

import java.util.List;

import javax.transaction.Transactional;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/items")
public class PantryItemResource {
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<PantryItem> getItems() {
        return PantryItem.findAll().list();
    }

    @Transactional
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public PantryItem postItem(PantryItem item) {
        PantryItem.persist(item);

        return item;
    }

    @Transactional
    @PUT
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public PantryItem putItem(@PathParam("id") Long id, PantryItem item) {
        if (item.id.equals(id)) {
            PantryItem.persist(item);
        } else {
            throw new WebApplicationException(Response.status(400).entity("ID does not match body").build());
        }

        return item;
    }

    @Transactional
    @DELETE
    @Path("/{id}")
    public void deleteItem(@PathParam("id") Long id) {
        boolean result = PantryItem.deleteById(id);

        if (!result) {
            throw new WebApplicationException(Response.status(404).entity("Could not find item").build());
        }
    }
}