Duck Controller

Creating the server endpoints for the Duck namespace

The last part of the current lesson includes how to hook the model to the router, and trust me, it is pretty much as simple as it sounds. To do this, we will use a controller to handle the logic.

As last time let's start by adding some new helper functions in oursrc/utils.ts:

  • getReqBody simply reads the request body as a json object and returns it. A nice shorthand to not having to type out the chaining.

  • getParamFromPath returns the param from the path by key, or throws if not in path. The key defaults to id.

  • getParamIntFromPath works the same as getParamFromPath with the adition of parsing it as an int.

Now that we have these helpers, we can get started on the controller logic.

Create a file called controller.ts in the duck folder, and add the following:

These methods are pretty straight forward. First we are getting the id and body from the request, then pass it along to the service, and then return an ok response.

These methods will be directly used instead of our current placeholderEndpoint in our router.ts, which is why we use the type AppRouterMiddleware. The middleware gives us the context as the first argument, which is what we will use to access the incoming data.


This page is a preview of Build and deploy a REST API with Deno

Start a new discussion. All notification go to the author.