Home

Awesome

@fastify/restartable

NPM version CI js-standard-style

Restart Fastify without losing a request.

This module is useful if you want to compose the fastify routes dynamically or you need some remote config. In case of a change, you can restart Fastify.

Install

npm i @fastify/restartable

Usage

import { restartable } from '@fastify/restartable'

async function createApp (fastify, opts) {
  const app = fastify(opts)

  app.get('/restart', async () => {
    await app.restart()
    return { status: 'ok' }
  })

  app.addHook('onClose', async () => {
    if(!app.closingRestartable) {
      console.log('closing the app because of restart')
    }
    else{
      console.log('closing the app because server is stopping')
    }
  })

  return app
}

const app = await restartable(createApp, { logger: true })
const host = await app.listen({ port: 3000 })

console.log('server listening on', host)

// call restart() if you want to restart
process.on('SIGUSR1', () => {
  console.log('Restarting the server')
  app.restart()
})

process.once('SIGINT', () => {
  console.log('Stopping the server')
  app.close()
})

Hooks

Example:

  async function createApplication (fastify, opts) {
    console.log('creating new app instance')
    return fastify(opts)
  }
  const app = await restartable(createApplication)

  app.addPreRestartHook(async (app) => {
    console.log('preRestart hook called')
  })

  app.addOnRestartHook(async (app) => {
    console.log('onRestart hook called')
  })

  await app.restart()

Output:

preRestart hook called
creating new app instance
onRestart hook called

License

MIT