Newer
Older
docker-demo / src / resources / ShoppingItemResource.java
package resources;

import dao.ShoppingDAO;
import domain.ShoppingItem;
import org.jooby.Err;
import org.jooby.Jooby;
import org.jooby.MediaType;
import org.jooby.Status;

public class ShoppingItemResource extends Jooby {

	public ShoppingItemResource(ShoppingDAO dao) {

		path("/api/items/item", () -> {

			/**
			 * Get an item.
			 *
			 * @param name The item's name.
			 * @return The item matching the given name.
			 */
			get("/:name", (req) -> {
				String name = req.param("name").value();

				if (dao.exists(name)) {
					return dao.getByName(name);
				} else {
					throw new Err(Status.NOT_FOUND, "No item matches that name");
				}

			});

			/**
			 * Delete an item from the list.
			 *
			 * @param name The name of the item to delete.
			 */
			delete("/:name", (req, rsp) -> {
				String name = req.param("name").value();

				if (dao.exists(name)) {
					dao.delete(name);
					rsp.status(Status.NO_CONTENT);
				} else {
					rsp.status(Status.NOT_FOUND);
				}
			});

			/**
			 * Update an existing item.
			 *
			 * @param name The name of the item to update.
			 * @param body The new details for the item.
			 */
			put("/:name", (req, rsp) -> {
				String name = req.param("name").value();
				ShoppingItem item = req.body().to(ShoppingItem.class);

				// make sure the names match an existing item or there is a conflict that will likely cause data corruption in the database (PKs should always be immutable)
				if (name.equals(item.getName()) && dao.exists(name)) {
					dao.updateItem(name, item);
					rsp.status(Status.ACCEPTED);
				} else {
					rsp.status(Status.CONFLICT);
				}
			});

		}).produces(MediaType.json).consumes(MediaType.json);

	}

}