@fastify/restartable
TypeScript icon, indicating that this package has built-in type declarations

2.3.0 • Public • Published

@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

  • preRestart - called before the creating a new app instance and closing an existing one. The hook is called with the current app instance as an argument. Use it to close any resources that you don't want to be shared between the app instances.

  • onRestart - called after the new app instance is created and the old one is closed. The hook is called with the new app instance as an argument.

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

Package Sidebar

Install

npm i @fastify/restartable

Weekly Downloads

123,374

Version

2.3.0

License

MIT

Unpacked Size

44.3 kB

Total Files

18

Last publish

Collaborators

  • gurgunday
  • metcoder95
  • galvez
  • simenb
  • coopflow
  • simoneb
  • rafaelgss
  • starptech
  • delvedor
  • matteo.collina
  • allevo
  • jsumners
  • zekth
  • eomm
  • fox1t
  • airhorns
  • kibertoad
  • climba03003
  • ivan-tymoshenko