Sunday, April 11, 2021

Still Using Java: Inventory Service

 Today we want to continue creating the Inventory Service with Quarkus. Here is a simple idea.








The item lifecycle (I made it up)












1. scaffold the project

mvn io.quarkus:quarkus-maven-plugin:1.13.1.Final:create \
    -DprojectGroupId=blog.technodeck \
    -DprojectArtifactId=inventory-service \
    -Dverison=0.0.1-SNAPSHOT \
    -Dextensions="resteasy-jackson,jdbc-h2,hibernate-orm-panache"


2. configure the database

# configure your datasource
quarkus.datasource.db-kind = h2
quarkus.datasource.username = sa
quarkus.datasource.password = sa
quarkus.datasource.jdbc.url = jdbc:h2:~/inventory-database
# drop and create the database at startup (use `update` to only update the schema)
quarkus.hibernate-orm.database.generation = update


3. Create Category bean and Product bean 

@Entity
public class Category extends PanacheEntity {

    public String name;
    public String description;
    
}

// ---

public enum ProductState {

    CREATED,
    LISTING,
    IN_CART,
    CHECKOUT,
    SHIP,
    RETURNED,
    DELIVERED
    
}

// ---

@Entity
public class Product extends PanacheEntity {
    public Long categoryId;
    public String name;
    public String description;
    public Float price;
    @Enumerated(EnumType.STRING)
    public ProductState state;
}

4. Create all the endpoint

@Path("/inventory")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class InventoryResource {

    @Transactional
    @POST
    @Path("/category")
    public String createCategory(List<Category> categories) {
        Category.persist(categories);
        return "OK";
    }
    
    @GET
    @Path("/category")
    public List<Category> listCategory() {
        return Category.listAll(Sort.ascending("name"));
    }
    
    @Transactional
    @POST
    @Path("/product")
    public String addProduct(List<Product> products) {
        products.forEach(p -> {p.state = ProductState.CREATED;});
        Product.persist(products);
        return "OK";
    }
    
    @GET
    @Path("/product")
    public List<Product> listProducts() {
        PanacheQuery<Product> products = Product.findAll(Sort.ascending("id"));
        products.page(Page.ofSize(10)); // first 10 records
        return products.list();
    }
    
    @GET
    @Path("/category/{categoryId}/product")
    public List<Product> listCategoryProducts(@PathParam("categoryId") Long categoryId) {
        return Product.list("categoryId", categoryId);
    }

5. And the results

Add Category




















List Categories























Add Product



List Product
























This service may look simple and straight forward. Things will get more interesting when I integrate the authentication service and inventory service together in the next post. So stay tuned.

Source Code: https://github.com/devilkazuya99/inventory-service





No comments: