Newer
Older
labs / tiddlers / content / labs / lab07 / $__Labs_07_Create the Module.md

The web service API for this module looks like:

URI HTTP Verb DAO Operation
/api/customers/{username} GET getCustomer(username)
/api/register POST saveCustomer(customer)

We are using two different paths (/api/customers and /api/register) here because we will need to differentiate these operations when we implement authentication in a later lab. The GET operation should require the user to be authenticated, but the POST operation should not (otherwise the user would need to authenticate before they could create an account which is a catch-22). Having different URI paths makes it easier to differentiate the operations.

  1. Create a new module class named CustomerModule for managing customer accounts. Use the ProductModule as a guide. Don't forget to inject the DAO into the constructor.

  2. Implement the GET operation using the ProductModule as a guide.

  3. The POST operation looks like this:

    post("/api/register", ctx -> {
        Customer customer = ctx.body().to(Customer.class);
        custDao.saveCustomer(customer);
        return ctx.send(StatusCode.CREATED);
    });

    Jooby is taking the request message body and converting it into a Customer object for us. The only reason that this works is that the message body is going to be JSON encoded and we have added the Gson module to the filter chain. Gson is doing the hard work for you.

    The last line of code is about returning a useful response to the client. This sends a 201/Created response (https://httpstatuses.com/201) to inform the client that a resource was created in response to their request.

  4. Add a line of code to the server constructor that mounts the customer module. You will need to create a Customer DAO field and pass it into the module.

  5. Run the server. Enter the URI for one of the customers in the DAO (you should be able to work out what URI you need). There are some hard-coded customers in the DAO that you can use for testing with.

    Leave this page open since we will use the JSON in the next section.