All Projects → fastify → fastify-awilix

fastify / fastify-awilix

Licence: MIT license
Dependency injection support for fastify

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to fastify-awilix

fastify-autoroutes
fastest way to map directories to URLs in fastify
Stars: ✭ 70 (+34.62%)
Mutual labels:  fastify, fastify-plugin
fastify-file-upload
Fastify plugin for uploading files
Stars: ✭ 68 (+30.77%)
Mutual labels:  fastify, fastify-plugin
session
Session plugin for fastify
Stars: ✭ 52 (+0%)
Mutual labels:  fastify, fastify-plugin
fastify-cron
Run cron jobs alongside your Fastify server 👷
Stars: ✭ 32 (-38.46%)
Mutual labels:  fastify, fastify-plugin
fastify-vue
A nuxt.js fastify plugin
Stars: ✭ 27 (-48.08%)
Mutual labels:  fastify, fastify-plugin
fastify-leveldb
Plugin to share a common LevelDB connection across Fastify.
Stars: ✭ 19 (-63.46%)
Mutual labels:  fastify, fastify-plugin
fastify-etag
Automatically generate etags for HTTP responses, for Fastify
Stars: ✭ 61 (+17.31%)
Mutual labels:  fastify, fastify-plugin
fastify-axios
Add axios http client to your fastify instance
Stars: ✭ 28 (-46.15%)
Mutual labels:  fastify, fastify-plugin
fastify-openapi-glue
A plugin for Fastify to autogenerate a configuration based on a OpenApi(v2/v3) specification.
Stars: ✭ 94 (+80.77%)
Mutual labels:  fastify, fastify-plugin
fastify-cors
Fastify CORS
Stars: ✭ 212 (+307.69%)
Mutual labels:  fastify, fastify-plugin
fastify-csrf
A fastify csrf plugin.
Stars: ✭ 88 (+69.23%)
Mutual labels:  fastify, fastify-plugin
fastify-postgres
Fastify PostgreSQL connection plugin
Stars: ✭ 144 (+176.92%)
Mutual labels:  fastify, fastify-plugin
fastify-caching
A Fastify plugin to facilitate working with cache headers
Stars: ✭ 123 (+136.54%)
Mutual labels:  fastify, fastify-plugin
fastify-webpack-hmr
Webpack hot module reloading for Fastify
Stars: ✭ 29 (-44.23%)
Mutual labels:  fastify, fastify-plugin
fastify-vite
This plugin lets you load a Vite client application and set it up for Server-Side Rendering (SSR) with Fastify.
Stars: ✭ 497 (+855.77%)
Mutual labels:  fastify, fastify-plugin
create-fastify-app
An utility that help you to generate or add plugin to your Fastify project
Stars: ✭ 53 (+1.92%)
Mutual labels:  fastify, fastify-plugin
fastify-env
Fastify plugin to check environment variables
Stars: ✭ 129 (+148.08%)
Mutual labels:  fastify, fastify-plugin
fastify-hasura
A Fastify plugin to have fun with Hasura.
Stars: ✭ 30 (-42.31%)
Mutual labels:  fastify, fastify-plugin
fastify-passport
Use passport strategies for authentication within a fastify application
Stars: ✭ 150 (+188.46%)
Mutual labels:  fastify, fastify-plugin
fastify-loader
The route loader for the cool kids!
Stars: ✭ 17 (-67.31%)
Mutual labels:  fastify, fastify-plugin

@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 })

Then, register some modules for injection:

const { diContainer } = 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

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

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

Using classic injection mode

If you prefer classic injection, you can use it like this:

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

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

Advanced DI configuration

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].