• Stars
    star
    385
  • Rank 107,613 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 8 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Asynchronous bootstrapping of Node applications

avvio

CI NPM version js-standard-style

Asynchronous bootstrapping is hard, different things can go wrong, error handling and load order just to name a few. The aim of this module is to make it simple.

avvio is fully reentrant and graph-based. You can load components/plugins within plugins, and be still sure that things will happen in the right order. At the end of the loading, your application will start.

Install

To install avvio, simply use npm:

npm i avvio

Example

The example below can be found here and run using node example.js. It demonstrates how to use avvio to load functions / plugins in order.

'use strict'

const app = require('avvio')()

app
  .use(first, { hello: 'world' })
  .after((err, cb) => {
    console.log('after first and second')
    cb()
  })

app.use(third)

app.ready(function (err) {
  // the error must be handled somehow
  if (err) {
    throw err
  }
  console.log('application booted!')
})

function first (instance, opts, cb) {
  console.log('first loaded', opts)
  instance.use(second)
  cb()
}

function second (instance, opts, cb) {
  console.log('second loaded')
  process.nextTick(cb)
}

// async/await or Promise support
async function third (instance, opts) {
  console.log('third loaded')
}

API


avvio([instance], [options], [started])

Starts the avvio sequence. As the name suggests, instance is the object representing your application. Avvio will add the functions use, after and ready to the instance.

const server = {}

require('avvio')(server)

server.use(function first (s, opts, cb) {
  // s is the same of server
  s.use(function second (s, opts, cb) {
    cb()
  })
  cb()
}).after(function (err, cb) {
  // after first and second are finished
  cb()
})

Options:

  • expose: a key/value property to change how use, after and ready are exposed.
  • autostart: do not start loading plugins automatically, but wait for a call to .start()  or .ready().
  • timeout: the number of millis to wait for a plugin to load after which it will error with code ERR_AVVIO_PLUGIN_TIMEOUT. Default 0 (disabled).

Events:

  • 'start'  when the application starts
  • 'preReady' fired before the ready queue is run

The avvio function can also be used as a constructor to inherit from.

function Server () {}
const app = require('avvio')(new Server())

app.use(function (s, opts, done) {
  // your code
  done()
})

app.on('start', () => {
  // you app can start
})

app.use(func, [optsOrFunc]) => Thenable

Loads one or more functions asynchronously.

The function must have the signature: instance, options, done

However, if the function returns a Promise (i.e. async), the above function signature is not required.

Plugin example:

function plugin (server, opts, done) {
  done()
}

app.use(plugin)

done should be called only once, when your plugin is ready to go. Additional calls to done are ignored.

use returns a thenable wrapped instance on which use is called, to support a chainable API that can also be awaited.

This way, async/await is also supported and use can be awaited instead of using after.

Example using after:

async function main () {
  console.log('begin')
  app.use(async function (server, opts) {
    await sleep(10)
    console.log('this first')
  })
  app.after(async (err) => {
    if (err) throw err
    console.log('then this')
  })
  await app.ready()
  console.log('ready')
}
main().catch((err) => console.error(err))

Example using await after:

async function main () {
  console.log('begin')
  app.use(async function (server, opts) {
    await sleep(10)
    console.log('this first')
  })
  await app.after()
  console.log('then this')
  await app.ready()
  console.log('ready')
}
main().catch((err) => console.error(err))

Example using await use:

async function main () {
  console.log('begin')
  await app.use(async function (server, opts) {
    await sleep(10)
    console.log('this first')
  })
  console.log('then this')
  await app.ready()
  console.log('ready')
}
main().catch((err) => console.error(err))

A function that returns the options argument instead of an object is supported as well:

function first (server, opts, done) {
  server.foo = 'bar'
  done()
}

function second (server, opts, done) {
  console.log(opts.foo === 'bar') // Evaluates to true
  done()
}

/**
 * If the options argument is a function, it has access to the parent
 * instance via the first positional variable
 */
const func = parent => {
  return {
    foo: parent.foo
  }
}

app.use(first)
app.use(second, func)

This is useful in cases where an injected variable from a plugin needs to be made available to another.

It is also possible to use esm with import('./file.mjs'):

import boot from 'avvio'

const app = boot()
app.use(import('./fixtures/esm.mjs'))

Error handling

In order to handle errors in the loading plugins, you must use the .ready() method, like so:

app.use(function (instance, opts, done) {
  done(new Error('error'))
}, opts)

app.ready(function (err) {
  if (err) throw err
})

When an error happens, the loading of plugins will stop until there is an after callback specified. Otherwise, it will be handled in ready.


app.after(func(error, [context], [done]))

Calls a function after all the previously defined plugins are loaded, including all their dependencies. The 'start' event is not emitted yet.

Note: await after can be used as an awaitable alternative to after(func), or await use can be also as a shorthand for use(plugin); await after().

The callback changes based on the parameters you give:

  1. If no parameter is given to the callback and there is an error, that error will be passed to the next error handler.
  2. If one parameter is given to the callback, that parameter will be the error object.
  3. If two parameters are given to the callback, the first will be the error object, the second will be the done callback.
  4. If three parameters are given to the callback, the first will be the error object, the second will be the top level context and the third the done callback.

In the "no parameter" and "one parameter" variants, the callback can return a Promise.

const server = {}
const app = require('avvio')(server)

...
// after with one parameter
app.after(function (err) {
  if (err) throw err
})

// after with two parameter
app.after(function (err, done) {
  if (err) throw err
  done()
})

// after with three parameters
app.after(function (err, context, done) {
  if (err) throw err
  assert.equal(context, server)
  done()
})

// async after with one parameter
app.after(async function (err) {
  await sleep(10)
  if (err) {
    throw err
  }
})

// async after with no parameter
app.after(async function () {
  await sleep(10)
})

done must be called only once.

If called with a function, it returns the instance on which after is called, to support a chainable API.


await app.after() | app.after() => Promise

Calling after with no function argument loads any plugins previously registered via use and returns a promise, which resolves when all plugins registered so far have loaded.

async function main () {
  app.use(async function (server, opts) {
    await sleep(10)
    console.log('this first')
  })
  app.use(async function (server, opts) {
    await sleep(10)
    console.log('this second')
  })
  console.log('before after')
  await app.after()
  console.log('after after')
  app.use(async function (server, opts) {
    await sleep(10)
    console.log('this third')
  })
  await app.ready()
  console.log('ready')
}
main().catch((err) => console.error(err))

Unlike after and use, await after is not chainable.


app.ready([func(error, [context], [done])])

Calls a function after all the plugins and after call are completed, but before 'start' is emitted. ready callbacks are executed one at a time.

The callback changes based on the parameters you give:

  1. If no parameter is given to the callback and there is an error, that error will be passed to the next error handler.
  2. If one parameter is given to the callback, that parameter will be the error object.
  3. If two parameters are given to the callback, the first will be the error object, the second will be the done callback.
  4. If three parameters are given to the callback, the first will be the error object, the second will be the top level context unless you have specified both server and override, in that case the context will be what the override returns, and the third the done callback.

If no callback is provided ready will return a Promise that is resolved or rejected once plugins and after calls are completed. On success context is provided to the .then callback, if an error occurs it is provided to the .catch callback.

const server = {}
const app = require('avvio')(server)
...
// ready with one parameter
app.ready(function (err) {
  if (err) throw err
})

// ready with two parameter
app.ready(function (err, done) {
  if (err) throw err
  done()
})

// ready with three parameters
app.ready(function (err, context, done) {
  if (err) throw err
  assert.equal(context, server)
  done()
})

// ready with Promise
app.ready()
  .then(() => console.log('Ready'))
  .catch(err => {
    console.error(err)
    process.exit(1)
  })

// await ready from an async function.
async function main () [
  try {
    await app.ready()
    console.log('Ready')
  } catch(err) {
    console.error(err)
    process.exit(1)
  }
}

done must be called only once.

The callback form of this function has no return value.

If autostart: false is passed as an option, calling .ready()  will also start the boot sequence.


app.start()

Start the boot sequence, if it was not started yet. Returns the app instance.


avvio.express(app)

Same as:

const app = express()
const avvio = require('avvio')

avvio(app, {
  expose: {
    use: 'load'
  }
})

app.override(server, plugin, options)

Allows overriding the instance of the server for each loading plugin. It allows the creation of an inheritance chain for the server instances. The first parameter is the server instance and the second is the plugin function while the third is the options object that you give to use.

const assert = require('assert')
const server = { count: 0 }
const app = require('avvio')(server)

console.log(app !== server, 'override must be set on the Avvio instance')

app.override = function (s, fn, opts) {
  // create a new instance with the
  // server as the prototype
  const res = Object.create(s)
  res.count = res.count + 1

  return res
}

app.use(function first (s1, opts, cb) {
  assert(s1 !== server)
  assert(Object.prototype.isPrototypeOf.call(server, s1))
  assert(s1.count === 1)
  s1.use(second)
  cb()

  function second (s2, opts, cb) {
    assert(s2 !== s1)
    assert(Object.prototype.isPrototypeOf.isPrototypeOf.call(s1, s2))
    assert(s2.count === 2)
    cb()
  }
})

app.onClose(func([context], [done]))

Registers a new callback that will be fired once then close api is called.

The callback changes basing on the parameters you give:

  1. If one parameter is given to the callback, that parameter will be the context.
  2. If zero or one parameter is given, the callback may return a promise
  3. If two parameters are given to the callback, the first will be the top level context unless you have specified both server and override, in that case the context will be what the override returns, the second will be the done callback.
const server = {}
const app = require('avvio')(server)
...
// onClose with one parameter
app.onClose(function (context) {
  // ...
})

// onClose with one parameter, returning a promise
app.onClose(function (context) {
  return new Promise((resolve, reject) => {
    // ...
  })
})

// async onClose with one parameter
app.onClose(async function (context) {
  // ...
  await ...
})


// onClose with two parameter
app.onClose(function (context, done) {
  // ...
  done()
})

If the callback returns a promise, the next onClose callback and the close callback will not run until the promise is either resolved or rejected.

done must be called only once. Returns the instance on which onClose is called, to support a chainable API.


app.close(func(error, [context], [done]))

Starts the shutdown procedure, the callback is called once all the registered callbacks with onClose has been executed.

The callback changes based on the parameters you give:

  1. If one parameter is given to the callback, that parameter will be the error object.
  2. If two parameters are given to the callback, the first will be the error object, the second will be the done callback.
  3. If three parameters are given to the callback, the first will be the error object, the second will be the top level context unless you have specified both server and override, in that case the context will be what the override returns, and the third the done callback.

If no callback is provided close will return a Promise.

const server = {}
const app = require('avvio')(server)
...
// close with one parameter
app.close(function (err) {
  if (err) throw err
})

// close with two parameter
app.close(function (err, done) {
  if (err) throw err
  done()
})

// close with three parameters
app.close(function (err, context, done) {
  if (err) throw err
  assert.equal(context, server)
  done()
})

// close with Promise
app.close()
  .then(() => console.log('Closed'))
  .catch(err => {
    console.error(err)
    process.exit(1)
  })

done must be called only once.


avvio.toJSON()

Return a JSON tree representing the state of the plugins and the loading time. Call it on preReady to get the complete tree.

const avvio = require('avvio')()
avvio.on('preReady', () => {
  avvio.toJSON()
})

The output is like this:

{
  "label": "bound root",
  "start": 1550245184665,
  "nodes": [
    {
      "parent": "bound root",
      "start": 1550245184665,
      "label": "first",
      "nodes": [
        {
          "parent": "first",
          "start": 1550245184708,
          "label": "second",
          "nodes": [],
          "stop": 1550245184709,
          "diff": 1
        }
      ],
      "stop": 1550245184709,
      "diff": 44
    },
    {
      "parent": "bound root",
      "start": 1550245184709,
      "label": "third",
      "nodes": [],
      "stop": 1550245184709,
      "diff": 0
    }
  ],
  "stop": 1550245184709,
  "diff": 44
}

avvio.prettyPrint()

This method will return a printable string with the tree returned by the toJSON() method.

const avvio = require('avvio')()
avvio.on('preReady', () => {
  console.log(avvio.prettyPrint())
})

The output will be like:

avvio 56 ms
├── first 52 ms
├── second 1 ms
└── third 2 ms

Acknowledgements

This project was kindly sponsored by nearForm.

License

Copyright Matteo Collina 2016-2020, Licensed under MIT.

More Repositories

1

fastify

Fast and low overhead web framework, for Node.js
JavaScript
29,975
star
2

fast-json-stringify

2x faster than JSON.stringify()
JavaScript
3,341
star
3

fastify-dx

Archived
JavaScript
909
star
4

fastify-vite

Fastify plugin for Vite integration.
JavaScript
795
star
5

fastify-swagger

Swagger documentation generator for Fastify
JavaScript
643
star
6

fastify-cli

Run a Fastify application with one command!
JavaScript
605
star
7

benchmarks

Fast and low overhead web framework fastify benchmarks.
JavaScript
502
star
8

fluent-json-schema

A fluent API to generate JSON schemas
JavaScript
479
star
9

aws-lambda-fastify

Insipired by aws-serverless-express to work with Fastify with inject functionality.
JavaScript
479
star
10

fastify-nextjs

React server side rendering support for Fastify with Next
JavaScript
450
star
11

fastify-sensible

Defaults for Fastify that everyone can agree on
JavaScript
405
star
12

fastify-static

Plugin for serving static files as fast as possible
JavaScript
396
star
13

fastify-multipart

Multipart support for Fastify
JavaScript
343
star
14

fastify-jwt

JWT utils for Fastify
JavaScript
340
star
15

fastify-rate-limit

A low overhead rate limiter for your routes
JavaScript
335
star
16

fastify-http-proxy

Proxy your http requests to another server, with hooks.
JavaScript
310
star
17

fastify-helmet

Important security headers for Fastify
JavaScript
305
star
18

fastify-websocket

basic websocket support for fastify
JavaScript
290
star
19

fastify-cors

Fastify CORS
JavaScript
276
star
20

point-of-view

Template rendering plugin for Fastify
JavaScript
272
star
21

fastify-auth

Run multiple auth functions in Fastify
JavaScript
268
star
22

fastify-example-twitter

Fastify example - clone twitter
JavaScript
262
star
23

docs-chinese

Fastify 中文文档
253
star
24

light-my-request

Fake HTTP injection library
JavaScript
243
star
25

fastify-autoload

Require all plugins in a directory
JavaScript
242
star
26

under-pressure

Measure process load with automatic handling of "Service Unavailable" plugin for Fastify.
JavaScript
234
star
27

fastify-passport

Use passport strategies for authentication within a fastify application
TypeScript
234
star
28

fastify-oauth2

Enable to perform login using oauth2 protocol
JavaScript
229
star
29

fastify-cookie

A Fastify plugin to add cookies support
JavaScript
224
star
30

middie

Middleware engine for Fastify.
JavaScript
206
star
31

fastify-mongodb

Fastify MongoDB connection plugin
JavaScript
200
star
32

fastify-express

Express compatibility layer for Fastify
JavaScript
190
star
33

secure-json-parse

JSON.parse() drop-in replacement with prototype poisoning protection
JavaScript
176
star
34

fastify-env

Fastify plugin to check environment variables
JavaScript
175
star
35

fastify-caching

A Fastify plugin to facilitate working with cache headers
JavaScript
163
star
36

fast-proxy

Node.js framework agnostic library that enables you to forward an http request to another HTTP server. Supported protocols: HTTP, HTTPS, HTTP2
JavaScript
163
star
37

fastify-plugin

Plugin helper for Fastify
JavaScript
159
star
38

fastify-compress

Fastify compression utils
JavaScript
157
star
39

env-schema

Validate your env variable using Ajv and dotenv
JavaScript
154
star
40

fastify-redis

Plugin to share a common Redis connection across Fastify.
JavaScript
151
star
41

github-action-merge-dependabot

This action automatically approves and merges dependabot PRs.
JavaScript
151
star
42

fastify-secure-session

Create a secure stateless cookie session for Fastify
JavaScript
145
star
43

fastify-postgres

Fastify PostgreSQL connection plugin
JavaScript
145
star
44

fastify-reply-from

fastify plugin to forward the current http request to another server
JavaScript
142
star
45

fastify-request-context

Request-scoped storage support, based on Asynchronous Local Storage (with fallback to cls-hooked)
JavaScript
138
star
46

fastify-type-provider-typebox

A Type Provider for Typebox
TypeScript
136
star
47

fastify-bearer-auth

A Fastify plugin to require bearer Authorization headers
JavaScript
136
star
48

csrf-protection

A fastify csrf plugin.
JavaScript
127
star
49

fastify-formbody

A Fastify plugin to parse x-www-form-urlencoded bodies
JavaScript
125
star
50

fastify-circuit-breaker

A low overhead circuit breaker for your routes
JavaScript
113
star
51

fastify-swagger-ui

Serve Swagger-UI for Fastify
JavaScript
100
star
52

example

Runnable examples of Fastify
JavaScript
96
star
53

create-fastify

Rapidly generate a Fastify project
JavaScript
92
star
54

fastify-routes

Decorates fastify instance with a map of routes
JavaScript
91
star
55

session

Session plugin for fastify
JavaScript
89
star
56

restartable

Restart Fastify without losing a request
JavaScript
86
star
57

fastify-schedule

Fastify plugin for scheduling periodic jobs.
JavaScript
76
star
58

website-metalsmith

This project is used to build the website for fastify web framework and publish it online.
HTML
76
star
59

fastify-awilix

Dependency injection support for fastify
JavaScript
75
star
60

fastify-error

JavaScript
74
star
61

fast-uri

Dependency free RFC 3986 URI toolbox
JavaScript
74
star
62

fastify-hotwire

Use the Hotwire pattern with Fastify
JavaScript
69
star
63

fastify-etag

Automatically generate etags for HTTP responses, for Fastify
JavaScript
69
star
64

fastify-funky

Make fastify functional! Plugin, adding support for fastify routes returning functional structures, such as Either, Task or plain parameterless function.
JavaScript
68
star
65

fastify-example-todo

A Simple Fastify REST API Example
JavaScript
64
star
66

fastify-accepts

Add accepts parser to fastify
JavaScript
63
star
67

help

Need help with Fastify? File an Issue here.
61
star
68

fastify-basic-auth

Fastify basic auth plugin
JavaScript
59
star
69

fastify-mysql

JavaScript
57
star
70

busboy

A streaming parser for HTML form data for node.js
JavaScript
56
star
71

fastify-url-data

A plugin to provide access to the raw URL components
JavaScript
55
star
72

releasify

A tool to release in a simpler way your module
JavaScript
55
star
73

fastify-kafka

Fastify plugin to interact with Apache Kafka.
JavaScript
51
star
74

fastify-elasticsearch

Fastify plugin for Elasticsearch
JavaScript
40
star
75

fastify-routes-stats

provide stats for routes using perf_hooks, for fastify
JavaScript
40
star
76

deepmerge

Merges the enumerable properties of two or more objects deeply. Fastest implementation of deepmerge
JavaScript
39
star
77

manifetch

A manifest-based fetch() API client builder.
JavaScript
37
star
78

fastify-response-validation

A simple plugin that enables response validation for Fastify.
JavaScript
36
star
79

fastify-type-provider-json-schema-to-ts

A Type Provider for json-schema-to-ts
TypeScript
32
star
80

skeleton

Template repository to create standardized Fastify plugins.
31
star
81

fastify-accepts-serializer

Serializer according to the accept header
JavaScript
24
star
82

website

JavaScript
24
star
83

fastify-leveldb

Plugin to share a common LevelDB connection across Fastify.
JavaScript
21
star
84

tsconfig

Shared TypeScript configuration for fastify projects
21
star
85

fastify-flash

Flash message plugin for Fastify
TypeScript
20
star
86

process-warning

A small utility for creating warnings and emitting them.
JavaScript
19
star
87

docs-korean

18
star
88

one-line-logger

JavaScript
18
star
89

fastify-api

A radically simple API routing and method injection plugin for Fastify.
JavaScript
18
star
90

ajv-compiler

Build and manage the AJV instances for the fastify framework
JavaScript
17
star
91

fastify-early-hints

Draft plugin of the HTTP 103 implementation
JavaScript
17
star
92

vite-plugin-blueprint

Vite plugin for shadowing files from a blueprint folder.
JavaScript
17
star
93

fastify-bankai

Bankai assets compiler for Fastify
JavaScript
15
star
94

fastify-diagnostics-channel

Plugin to deal with diagnostics_channel on Fastify
JavaScript
14
star
95

csrf

CSRF utilities for fastify
JavaScript
13
star
96

.github

Default community health files
13
star
97

any-schema-you-like

Save multiple schemas and decide which one to use to serialize the payload
JavaScript
13
star
98

fastify-throttle

Throttle the download speed of a request
JavaScript
12
star
99

fastify-typescript-extended-sample

This project is supposed to be a large, fake Fastify & TypeScript app. It is meant to be a reference as well as a pseudo-sandbox for Fastify TypeScript changes.
TypeScript
11
star
100

fastify-soap-client

Fastify plugin for a SOAP client
JavaScript
10
star