Create a Hapi Server with Knex and MySQL

  1. Debugging

In this article I am going to show you how to build a simple API server with hapi and MySQL. I am using Knex as a SQL query builder. And in order to pass the database instance to the request object, I use server decorations property. Rest of the code consists of a simple procedure explained here in detail. To see it in action follow the steps below:

  1. Setup the project and install dependencies:
1
2
3
mkdir myServer
cd myServer
npm -y init
  1. Install dependencies:
1
npm i @hapi/hapi mysql2 knex
  1. Create a file named server.js with the contents below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const hapi = require("@hapi/hapi");
const knex = require("knex");

// Controller function for '/doesTableExist' route
function test(req, res) {
// We can access our database over request object
return req.database.schema.hasTable("users").then(function (exists) {
// Check if users table exists in the database and return the JSON object below
return {
doesTableExist: exists,
};
});
}

async function run() {
// Define server with its options
const server = hapi.server({
port: 3000,
host: "localhost",
});

// Define routes array
const routes = [
{
method: "GET", // Method of the route
path: "/doesTableExist", // Path of the route
handler: test, // Handler aka controller of the route
},
];

server.route(routes);

// Create a database instance
const database = knex({
client: "mysql2", // Database client
connection: {
host: "localhost",
user: "root",
password: "root",
database: "myDatabase",
},
});

// Attach database instance to request object under the name of 'database'
server.decorate("request", "database", database);

// Initialize the server
await server.start();

console.log(`Running`);
}

run();
  1. Configure and run your MySQL server and modify database instance with proper values(host, user, password, database). If you want to use another SQL database check out the supported clients here and install the one you need.

  2. Run the server with command below:

1
node server.js
  1. Check out the route we defined in our code to see it works:
1
http://localhost:3000/doesTableExist

Debugging

If you encounter some errors during development, such as this one:

1
2
3
4
5
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "An internal server error occurred"
}

You could enable debug mode in hapi, which will have your log events printed to the console.

For example, if you want to print any error in a request you would configure your server as follows:

1
const server = Hapi.server({ debug: { request: ['error'] } });