This video is available to students only

Using Knex with Express

Using Knex with an Express Application

Using Knex in the Backend App#

Previously, we created a knexfile that contained configuration for Knex Migrations to connect to our database. We can use the same knexfile in our backend Express app to allow it to work with the database.

We'll start by adding a directory in the root of the backend project called database and then create a JavaScript file that initializes Knex.

Create the fileclient.js in /school-lunch/backend/database:

Now let's take a look at the GET /lunch-week endpoint. Previously, we just returned a static, hard-coded array of lunch-week objects:

We can change it to use Knex and return data from the database like this:

Now, you can give it a try in your browser at http://localhost:3000/api/lunch-week. If everything works, you should see the following JSON response, based on the data from the lunch_week table.

Knex Stringcase#

You may have noticed that the JSON property names are in snake-case, just like the database column names. We can use a little bit of extra configuration to convert them to camelCase. Install the package knex-stringcase.

Then update the /database/client.js to use knex-stringcase as follows:

 

This page is a preview of Fullstack Svelte

No discussions yet