Abstracting database access
In order to connect to the database, we are going to use an abstraction layer by utilizing node-dbi
. This allows us to transparently use MySQL at a later point in time, without the need to change the code that does database operations.
First, we should change our spec in order to have it expect actual database content. A request to /api/keywords/
should return a JSON structure that carries an array of objects, where each object represents a keyword with its ID, value, and the ID of its category:
[ {"id": 1, "value": "Aubergine", "categoryID": 1}, {"id": 2, "value": "Onion", "categoryID": 1}, {"id": 3, "value": "Knife", "categoryID": 2} ]
A data structure like this would be stored in a relational database like this:


Note
In this structure, keyword.categoryID
is a foreign key to category.id
. For now, however, we will only work with the keyword
table.
Assuming the above example database content during a test run, our spec expectation needs to look like this...