Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Configuring Knex in an Express application
Cesare Ferrari
Cesare Ferrari

Posted on

     

Configuring Knex in an Express application

How to use a Knex configuration file in a REST API.

We have seen in a previous article how to generate a configuration file in order to connectKnex to a SQLite3 database.
The file, namedknexfile.js, was generated with theknex init command in our terminal, and placed at the root of our application, with some initial default configurations.

We also created a second file, calleddb-config.js, with code that creates and exports a Javascript object that we can use to actually issue queries to the database.
This is the code indb-config.js

// db-config.jsconstknex=require('knex');constconfig=require('../knexfile.js');constdb=knex(config.development);module.exports=db;

As you can see, we first require Knex, then theknexfile. We then create a newdb variable and assign to it whatever is returned by a call toknex() with the development configuration defined inknexfile.

Finally, we export thedb object.
Once we have adb object, we import it into a router file into our Express application.

Route handler

Let's imagine we have an application that provides anAPI with data about fruits. In our application we have configured a router file infruits/fruit-router.js

This file defines the route handlers for access to ourAPI endpoints. The route handlers will use thedb object to query the database.
At the top offruit-router.js we create aconst nameddb and assign to it the object exported bydb-config.js:

constdb=require('../data/db-config.js');

Once we have this object, we use it to query the database. Let's create a route handler that responds to aGET request and returns all the fruit records stored in the database.

As you might have guessed, we use theget() method of Express, because this is aGET request.
We make sure we use theasync/await syntax because we are dealing with promises:

router.get('/',async(req,res)=>{try{constfruits=awaitdb('fruits');res.status(200).json(fruits);}catch(err){res.status(500).json({message:"Problem getting fruits"});}})

The codedb('fruits') is all we need to connect to the database and return all records from the fruits table.

These records are in turn sent back to the client that made the request. In case of an error, we handle it with an error message.

If we try out this request with the InsomiaREST client, we confirm that everything is working correctly:

Get all fruits

A possible issue

It is considered a best practice to put theknexfile at the root of our application.
We have seen how we can create aknexfile.js by issuing theknex init command at the terminal.

Before we issue this command, though, we need to make sure we are at theroot of the project, becauseknex init will create aknexfile in the current location, which may inadvertently be inside a sub-folder in the project.

If you actually intend to put theknexfile in some other location besides the application root, you can do it, but make sure the paths that reference this file are adjusted accordingly.

Now that we have seen how to create and configure aknexfile, let's take a look at how to create database tables with knexmigrations.

We'll see how to set up a migration file in the next article.


I write daily about web development. If you like this article, feel free to share it with your friends and colleagues.

You can receive articles like this in your inbox bysubscribing to my newsletter.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I write daily about front-end and back-end web development.
  • Location
    Du Bois, PA
  • Education
    Full Stack Web Development @ Lambda School
  • Work
    Web application developer at Mary & Ferrari
  • Joined

More fromCesare Ferrari

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp