npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@fastify/awilix

v5.1.0

Published

Dependency injection support for fastify framework

Downloads

36,796

Readme

@fastify/awilix

NPM Version Build Status

Dependency injection support for fastify framework, using awilix.

Getting started

First install the package and awilix:

npm i @fastify/awilix awilix

Next, set up the plugin:

const { fastifyAwilixPlugin } = require('@fastify/awilix')
const fastify = require('fastify')

app = fastify({ logger: true })
app.register(fastifyAwilixPlugin, { 
  disposeOnClose: true, 
  disposeOnResponse: true,
  strictBooleanEnforced: true
})

Then, register some modules for injection:

const { 
  diContainer, // this is an alias for diContainerProxy
  diContainerClassic, // this instance will be used for `injectionMode = 'CLASSIC'`
  diContainerProxy // this instance will be used by default
} = require('@fastify/awilix')
const { asClass, asFunction, Lifetime } = require('awilix')

// Code from the previous example goes here

diContainer.register({
  userRepository: asClass(UserRepository, {
    lifetime: Lifetime.SINGLETON,
    dispose: (module) => module.dispose(),
  }),
})

app.addHook('onRequest', (request, reply, done) => {
  request.diScope.register({
    userService: asFunction(
      ({ userRepository }) => {
        return new UserService(userRepository, request.params.countryId)
      },
      {
        lifetime: Lifetime.SCOPED,
        dispose: (module) => module.dispose(),
      }
    ),
  })
  done()
})

Note that there is no strict requirement to use classes, it is also possible to register primitive values, using either asFunction(), or asValue(). Check awilix documentation for more details.

After all the modules are registered, they can be resolved with their dependencies injected from app-scoped diContainer and request-scoped diScope. Note that diScope allows resolving all modules from the parent diContainer scope:

app.post('/', async (req, res) => {
  const userRepositoryForReq = req.diScope.resolve('userRepository')
  const userRepositoryForApp = app.diContainer.resolve('userRepository') // This returns exact same result as the previous line
  const userService = req.diScope.resolve('userService')

  // Logic goes here

  res.send({
    status: 'OK',
  })
})

Plugin options

injectionMode - whether to use PROXY or CLASSIC injection mode. See awilix documentation for details. Default is 'PROXY'.

container - pre-created AwilixContainer instance that should be used by the plugin. By default plugin uses its own instance. Note that you can't specify both injectionMode and container parameters at the same time.

disposeOnClose - automatically invoke configured dispose for app-level diContainer hooks when the fastify instance is closed. Disposal is triggered within onClose fastify hook. Default value is true

disposeOnResponse - automatically invoke configured dispose for request-level diScope hooks after the reply is sent. Disposal is triggered within onResponse fastify hook. Default value is true

asyncInit - whether to process asyncInit fields in DI resolver configuration. Note that all dependencies with asyncInit enabled are instantiated eagerly. Disabling this will make app startup slightly faster. Default value is false

asyncDispose - whether to process asyncDispose fields in DI resolver configuration when closing the fastify app. Disabling this will make app closing slightly faster. Default value is false

eagerInject - whether to process eagerInject fields in DI resolver configuration, which instantiates and caches module immediately. Disabling this will make app startup slightly faster. Default value is false

strictBooleanEnforced - whether to throw an error if enabled field in a resolver configuration is set with unsupported value (anything different from true and false). It is recommended to set this to true, which will be a default value in the next semver major release. Default value is false

Defining classes

All dependency modules are resolved using either the constructor injection (for asClass) or the function argument (for asFunction), by passing the aggregated dependencies object, where keys of the dependencies object match keys used in registering modules:

class UserService {
  constructor({ userRepository }) {
    this.userRepository = userRepository
  }

  dispose() {
    // Disposal logic goes here
  }
}

class UserRepository {
  constructor() {
    // Constructor logic goes here
  }

  dispose() {
    // Disposal logic goes here
  }
}

diContainer.register({
  userService: asClass(UserRepository, {
    lifetime: Lifetime.SINGLETON,
    dispose: (module) => module.dispose(),
  }),
  userRepository: asClass(UserRepository, {
    lifetime: Lifetime.SINGLETON,
    dispose: (module) => module.dispose(),
  }),
})

Typescript usage

By default @fastify/awilix is using generic empty Cradle and RequestCradle interfaces, it is possible extend them with your own types:

awilix defines Cradle as a proxy, and calling getters on it will trigger a container.resolve for an according module. Read more

declare module '@fastify/awilix' {
  interface Cradle {
    userService: UserService
  }
  interface RequestCradle {
    user: User
  }
}
//later, type is inferred correctly
fastify.diContainer.cradle.userService
// or
app.diContainer.resolve('userService')
// request scope
request.diScope.resolve('userService')
request.diScope.resolve('user')

Find more in tests or in example from awilix documentation

Asynchronous init, dispose and eager injection

fastify-awilix supports extended awilix resolver options, provided by awilix-manager:

const { diContainer, fastifyAwilixPlugin } = '@fastify/awilix'
const { asClass } = require('awilix')

diContainer.register(
  'dependency1',
  asClass(AsyncInitSetClass, {
    lifetime: 'SINGLETON',
    asyncInit: 'init',
    asyncDispose: 'dispose',
    eagerInject: true,
  })
)

app = fastify()
await app.register(fastifyAwilixPlugin, { asyncInit: true, asyncDispose: true, eagerInject: true })
await app.ready()

Advanced DI configuration

For more advanced use-cases, check the official awilix documentation