Database

Database

Fastify’s ecosystem provides a handful of plugins for connecting to various database engines. This guide covers engines that have Fastify plugins maintained within the Fastify organization.

If a plugin for your database of choice does not exist you can still use the database as Fastify is database agnostic. By following the examples of the database plugins listed in this guide, a plugin can be written for the missing database engine.

If you would like to write your own Fastify plugin please take a look at the plugins guide

MySQL

Install the plugin by running npm i @fastify/mysql.

Usage:

  1. const fastify = require('fastify')()
  2. fastify.register(require('@fastify/mysql'), {
  3. connectionString: 'mysql://root@localhost/mysql'
  4. })
  5. fastify.get('/user/:id', function(req, reply) {
  6. fastify.mysql.query(
  7. 'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],
  8. function onResult (err, result) {
  9. reply.send(err || result)
  10. }
  11. )
  12. })
  13. fastify.listen({ port: 3000 }, err => {
  14. if (err) throw err
  15. console.log(`server listening on ${fastify.server.address().port}`)
  16. })

Postgres

Install the plugin by running npm i pg @fastify/postgres.

Example:

  1. const fastify = require('fastify')()
  2. fastify.register(require('@fastify/postgres'), {
  3. connectionString: 'postgres://postgres@localhost/postgres'
  4. })
  5. fastify.get('/user/:id', function (req, reply) {
  6. fastify.pg.query(
  7. 'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
  8. function onResult (err, result) {
  9. reply.send(err || result)
  10. }
  11. )
  12. })
  13. fastify.listen({ port: 3000 }, err => {
  14. if (err) throw err
  15. console.log(`server listening on ${fastify.server.address().port}`)
  16. })

Redis

Install the plugin by running npm i @fastify/redis

Usage:

  1. 'use strict'
  2. const fastify = require('fastify')()
  3. fastify.register(require('@fastify/redis'), { host: '127.0.0.1' })
  4. // or
  5. fastify.register(require('@fastify/redis'), { url: 'redis://127.0.0.1', /* other redis options */ })
  6. fastify.get('/foo', function (req, reply) {
  7. const { redis } = fastify
  8. redis.get(req.query.key, (err, val) => {
  9. reply.send(err || val)
  10. })
  11. })
  12. fastify.post('/foo', function (req, reply) {
  13. const { redis } = fastify
  14. redis.set(req.body.key, req.body.value, (err) => {
  15. reply.send(err || { status: 'ok' })
  16. })
  17. })
  18. fastify.listen({ port: 3000 }, err => {
  19. if (err) throw err
  20. console.log(`server listening on ${fastify.server.address().port}`)
  21. })

By default @fastify/redis doesn’t close the client connection when Fastify server shuts down. To opt-in to this behavior, register the client like so:

  1. fastify.register(require('@fastify/redis'), {
  2. client: redis,
  3. closeClient: true
  4. })

Mongo

Install the plugin by running npm i @fastify/mongodb

Usage:

  1. const fastify = require('fastify')()
  2. fastify.register(require('@fastify/mongodb'), {
  3. // force to close the mongodb connection when app stopped
  4. // the default value is false
  5. forceClose: true,
  6. url: 'mongodb://mongo/mydb'
  7. })
  8. fastify.get('/user/:id', async function (req, reply) {
  9. // Or this.mongo.client.db('mydb').collection('users')
  10. const users = this.mongo.db.collection('users')
  11. // if the id is an ObjectId format, you need to create a new ObjectId
  12. const id = this.mongo.ObjectId(req.params.id)
  13. try {
  14. const user = await users.findOne({ id })
  15. return user
  16. } catch (err) {
  17. return err
  18. }
  19. })
  20. fastify.listen({ port: 3000 }, err => {
  21. if (err) throw err
  22. })

LevelDB

Install the plugin by running npm i @fastify/leveldb

Usage:

  1. const fastify = require('fastify')()
  2. fastify.register(
  3. require('@fastify/leveldb'),
  4. { name: 'db' }
  5. )
  6. fastify.get('/foo', async function (req, reply) {
  7. const val = await this.level.db.get(req.query.key)
  8. return val
  9. })
  10. fastify.post('/foo', async function (req, reply) {
  11. await this.level.db.put(req.body.key, req.body.value)
  12. return { status: 'ok' }
  13. })
  14. fastify.listen({ port: 3000 }, err => {
  15. if (err) throw err
  16. console.log(`server listening on ${fastify.server.address().port}`)
  17. })

Writing plugin for a database library

We could write a plugin for a database library too (e.g. Knex, Prisma, or TypeORM). We will use Knex in our example.

  1. 'use strict'
  2. const fp = require('fastify-plugin')
  3. const knex = require('knex')
  4. function knexPlugin(fastify, options, done) {
  5. if(!fastify.knex) {
  6. const knex = knex(options)
  7. fastify.decorate('knex', knex)
  8. fastify.addHook('onClose', (fastify, done) => {
  9. if (fastify.knex === knex) {
  10. fastify.knex.destroy(done)
  11. }
  12. })
  13. }
  14. done()
  15. }
  16. export default fp(knexPlugin, { name: 'fastify-knex-example' })

Writing a plugin for a database engine

In this example, we will create a basic Fastify MySQL plugin from scratch (it is a stripped-down example, please use the official plugin in production).

  1. const fp = require('fastify-plugin')
  2. const mysql = require('mysql2/promise')
  3. function fastifyMysql(fastify, options, done) {
  4. const connection = mysql.createConnection(options)
  5. if (!fastify.mysql) {
  6. fastify.decorate('mysql', connection)
  7. }
  8. fastify.addHook('onClose', (fastify, done) => connection.end().then(done).catch(done))
  9. done()
  10. }
  11. export default fp(fastifyMysql, { name: 'fastify-mysql-example' })

Migrations

Database schema migrations are an integral part of database management and development. Migrations provide a repeatable and testable way to modify a database’s schema and prevent data loss.

As stated at the beginning of the guide, Fastify is database agnostic and any Node.js database migration tool can be used with it. We will give an example of using Postgrator which has support for Postgres, MySQL, SQL Server and SQLite. For MongoDB migrations, please check migrate-mongo.

Postgrator

Postgrator is Node.js SQL migration tool that uses a directory of SQL scripts to alter the database schema. Each file an migrations folder need to follow the pattern: [version].[action].[optional-description].sql.

version: must be an incrementing number (e.g. 001 or a timestamp).

action: should be do or undo. do implements the version, undo reverts it. Think about it like up and down in other migration tools.

optional-description describes which changes migration makes. Although optional, it should be used for all migrations as it makes it easier for everyone to know which changes are made in a migration.

In our example, we are going to have a single migration that creates a users table and we are going to use Postgrator to run the migration.

Run npm i pg postgrator to install dependencies needed for the example.

  1. // 001.do.create-users-table.sql
  2. CREATE TABLE IF NOT EXISTS users (
  3. id SERIAL PRIMARY KEY NOT NULL,
  4. created_at DATE NOT NULL DEFAULT CURRENT_DATE,
  5. firstName TEXT NOT NULL,
  6. lastName TEXT NOT NULL
  7. );
  1. const pg = require('pg')
  2. const Postgrator = require('postgrator')
  3. const path = require('node:path')
  4. async function migrate() {
  5. const client = new pg.Client({
  6. host: 'localhost',
  7. port: 5432,
  8. database: 'example',
  9. user: 'example',
  10. password: 'example',
  11. });
  12. try {
  13. await client.connect();
  14. const postgrator = new Postgrator({
  15. migrationPattern: path.join(__dirname, '/migrations/*'),
  16. driver: 'pg',
  17. database: 'example',
  18. schemaTable: 'migrations',
  19. currentSchema: 'public', // Postgres and MS SQL Server only
  20. execQuery: (query) => client.query(query),
  21. });
  22. const result = await postgrator.migrate()
  23. if (result.length === 0) {
  24. console.log(
  25. 'No migrations run for schema "public". Already at the latest one.'
  26. )
  27. }
  28. console.log('Migration done.')
  29. process.exitCode = 0
  30. } catch(err) {
  31. console.error(err)
  32. process.exitCode = 1
  33. }
  34. await client.end()
  35. }
  36. migrate()