Duck Service

Creating the methods to access the database

In the previous steps, we created a basic Duck interface and connected the database pool to our application. In this step, we will be adding a way for us to store and fetch the data we need.

When working on large applications, I usually structure my namespaces as such:

  • A Model to hold information about the database table and its structure

  • A DAO (Data Access Object) to be the connection point between the application and the database. This is where the queries are placed.

  • A Service serving as an entrypoint to the namespace. Usually contains distinkt namespace logic, and works as a bridge between the DAO and other code.

  • A Controller to be the entrypoint connected to the endpoints. Uses other services to provide logic and data.

There are other files and conventions, like guards to validate incoming requests, but we will not discuss them in this guide. In our case we will merge the DAO and the Service into one file to keep our app simple.

As with everything else, this is a design decision for our application. If you really wanted to, you could write everything in one file, but that wouldn't be very nice to work with as the file would quickly become quite big and convoluted. But remember, it always depends on your application, so in some cases it might be better, cleaner, or more efficient to have everything in one file. In short, it depends!

To get started on the service file, we will add some new imports to ourimport_map.json.

As we are also using the context of the Oak app to get our postgres client, we should add a helper function to get this out of the context.

Add this to our src/utils.ts file.

When you access ctx.state, it is simply a clone of the state, is the actual global state where you can access the pool.

As you can see, it would be quite tiresome to write this long chain every time so with this function, we can quicly return a pool client for us to use.

Lastly before we begin the core of this lesson, we will create a new filesrc/duck/service.ts, and add the following imports to it. We will be needing them for the functions we will create.

Create a Duck#

To create a Duck, we need to create a SQL query and also do some data validation. A Duck also contains a password, and as every good programmer knows, this shuld never be stored as clear text, but be hashed (notencrypted). We will discuss password hashing and authentication in two lessons. We also want to generate an id for every new entry.

Here is our implementation for the createDuck function:

We start our function by verifying the incoming data, and as we only have two fields to worry about, we can make it a bit simple for ourselves. We check if the username and password is set, and if not, we throw an http error which will be caught by our error middleware.


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

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