Fastify and PostgreSQL REST API
Enter the ‘speed force’
From the documentation, fastify is a fast and low overhead web framework for Node.js.
So, I decided to explore some of the awesome features that fastify offers including but not limited to, speed, extensibility via plugins and decorators, schema validation, and serialization and logging. I dived into their documentation, which is excellent by the way, with the help of some GitHub repositories and decided to build some REST API endpoints powered by fastify and a PostgreSQL database.
You can check out the source code or follow along in this post.
Getting Started
Setting up the project
Navigate to the root folder of your project and run npm init
to initialize your project. Create an src
folder for your project source code and create an index.js
file as the entry point.
Installing dependencies
Installing nodemon
nodemon is a dev dependency that’ll monitor your file changes and restart your server automatically.
You can install nodemon locally with npm:
1 | npm install nodemon --save-dev |
Add this npm script to the scripts in the package.json
file
1 | "start": "nodemon src/index.js" |
Installing Fastify
Install with npm:
1 | npm i fastify --save |
Hello World: Starting and running your server
In the index.js
file add this block of code:
1 | const fastify = require('fastify')({logger: true}) |
On the first line, we create a fastify instance and enable logging, fastify uses pino as its logger. We then define a GET
route method, specify a homepage endpoint '/'
and pass in the route handler function which responds with the object {hello: 'world'}
when we make a get request to the homepage.
We instantiate our fastify server instance (wrapped in our start
function) and listen for requests on port 3000. To start the server, run npm start
on your terminal in the root folder. You Server should now be running and the following will be logged in the terminal:
1 | {"level":30,"time":1618477680757,"pid":5800,"hostname":"x","msg":"Server listening at http://127.0.0.1:3000"} |
When you visit the homepage you should see the response:
1 | curl http://localhost:3000/ |
Great we have our server!
Plugins
We can extend fastify’s functionality with plugins.
From the documentation:
A plugin can be a set of routes, a server decorator, or whatever.
We can refactor our route into a plugin and put it in a separate file i.e routes.js
, then require it in our root file and use the register
API to add the route or other plugins.
Create a routes.js
file and add this code:
1 | async function routes(fastify, options) { |
We then require our module in index.js
and register it.
1 | const fastify = require('fastify')({logger: true}) |
A request on the homepage should still work. Great, we have our first plugin.
Creating our database
To create a database we first need to connect to psql
, an interactive terminal for working with Postgres.
To connect to psql
run the command in the terminal:
1 | psql -h localhost -U postgres |
Enter your password in the prompt to connect to psql
.
The CREATE DATABASE databaseName
statement creates a database:
1 | CREATE DATABASE todos |
To connect to the created database run the command:
1 | \c todos |
To create our table run the statement
1 | CREATE TABLE todos ( |
Connecting our database
To interface with postgreSQL database we need node-postgres or the pg
driver.
To install node-postgres
:
1 | npm install pg |
Database connection plugin
Let’s create a plugin to connect to our database. Create a db.js
file and add the following code:
1 | const fastifyPlugin = require('fastify-plugin') |
Let’s skip the fastifyPlugin
part first.
We require Client
module from node-postgres
and create a client
instance, passing in the object with the various fields.
Make sure to create a .env
file and add:
1 | PASSWORD='yourpassword' |
Install and require the dotenv
module to load the environment variables
1 | npm i dotenv |
We then create our dbconnector
plugin and inside the try block, we connect to our postgres database.
Inside the block you can also see:
1 | fastify.decorate('db', {client}) |
What is the decorate function?
In fastify, to add functionality to the fastify instance, you use decorators. We use the decorate
API, pass the property name 'db'
as the first argument and the value of our client
instance ({client}
) as the second argument. The value could also be a function or a string.
We export the plugin wrapped in a fastifyPlugin
module.
Require the module in the index.js
file and register it.
1 | const dbconnector = require('./db') |
We can now access our client instance in other parts of the application for instance in our routes to query data using fastify.db.client
.
Let’s take a step back to the fastifyPlugin
module. Why wrap our plugin with fastifyPlugin? When we register a plugin, we create a fastify context (encapsulation), which means access to the data outside our registered plugin is restricted. In this case, we can’t access our database client
instance using fastify.db.client
anywhere in our application.
To share context, we wrap our plugin in a fastifyPlugin
module. We can now access our database client
instance anywhere in our application.
Serialization
Lets refactor our homepage route to return information from our database:
1 | async function routes(fastify, options) { |
We First access our database client
instance and assign it to a client
variable.
Inside our routes we query all columns from our database using the shorthand *
and send the returned todos using reply.send(rows)
- you could also use return rows
.
Make sure you add some todos in your database first in the psql
terminal i.e:
1 | INSERT INTO todos (id, name, "createdAt", important, "dueDate", done) |
If an error occurs, trying to query our database, we throw the error.
When you look closer at our get route method, you can see have an object as our second argument with a schema
key and allTodos
as the value.
Fastify uses fast-json-stringify to serialize your response body when a schema is provided in the route options.
To add the schema create a schemas.js
file and add the allTodos schema
:
1 | const allTodos = { |
Fastify recommends using JSON Schema to serialize your outputs, you can read how to write JSON schema here.
We’re specifying the response
, the response status code
, and the entity which is an array
type. The items
specify each entry in the array as an object with the required keys and the properties with the various fields and types.
Remember to require the module in the routes.js
file.
Validation
In the routes.js
file, let’s add a POST
method route inside our route plugin to add todos to our database.
1 | fastify.post('/', {schema: addTodo}, async function(request, reply) { |
We allow the client to send a JSON object in the body with name
of the todo, important
, and dueDate
properties.
We then generate a unique id
, assign false to done
and a timestamp assigned to createdAt
.
To generate the unique id install uuid
:
1 | npm install uuid |
Require the module in the routes.js
:
1 | const { v4: uuidv4 } = require('uuid'); |
We then construct a query object with a text
property with the SQL statement to insert the todos in the database and the values
property containing the values to be inserted into the respective columns.
After a successful insert we send a 201 Created
status code back to the client.
In the schemas.js
file, let’s add the validation schema for our todos:
1 | const addTodo = { |
Fastify uses Ajv to validate requests.
We expect the client to always send the name
of the todo by adding it in the required property array.
The dueDate
property can be omitted by the client whereby it will be null
by default. This is made possible by setting the nullable
property to true
which allows a data instance to be JSON null. When provided it has to be of the format ‘date-time’.
The client
can optionally indicate whether a todo is important or it falls back to the default.
If the above conditions are not satisfied, fastify will automatically send an error object with the error message.
For instance, if you omit a name, you should see an error like
1 | { |
Great! Our validation is working
Adding other REST endpoints
Update todo
Let’s allow users to set their todo as done or importance of the todo or change dueDate. To do that let’s add a PATCH
method route to our routes plugin.
1 | fastify.patch('/:id',{schema: updateTodo}, async function (request, reply) { |
We’re extracting the id
of the todo we want to update from the parameter and the values from the request body.
We then create our query statement, updating the columns provided optionally using the COALESCE
function. That is, if the clients omit some properties in the JSON body, we update only the provided properties and leave the rest as they are in the todo row.
We then respond with a 204 No Content
.
Lets add a validation schema for our route:
1 | const updateTodo = { |
params validates the params object.
Delete todo
To delete a todo, we just need the id
sent in the URL parameter.
Add a DELETE
method route:
1 | fastify.delete('/:id', {schema: deleteTodo}, async function(request, reply) { |
Lets add a validation schema for our DELETE
route:
1 | const deleteTodo = { |
Conclusion:
Give fastify a try and “take your HTTP server to ludicrous speed” ~ Matteo Collina.
You can check out the project source code here
References:
- Fastify Documentation
- Understanding JSON schema
Fastify examples; GitHub repository:
- Fastify-example
- Fastify-example-todo