어제의 나보다 성장한 오늘의 나

[Nods.JS] fastify/awilix 을 이용한 DI 설계 (JS DI 라이브러리) 본문

Node.js

[Nods.JS] fastify/awilix 을 이용한 DI 설계 (JS DI 라이브러리)

today_me 2024. 2. 8. 00:22
반응형

 

 

 개발팀 내에서 빠른 생산성을 위해 fastify를 사용하기로 하였고 개발 도중 의존성 주입에 필요성을 느끼게 되어 awilix를 도입하고자 하였다. 이에 따라 오늘은 fastify에서 awilix를 어떻게 사용하는 에 대해서 알아보자.

 

 

 


 

 

 

 

 자바스크립트로 의존성 주입을 설계 하다보면 해당 클래스나 함수에 필요한 의존성들을 미리 등록해 두어야 한다. 이를 Awilix에서는 container로 관리한다. 필요한 의존성들은 미리 container에 등록(register) 해두고 필요한 곳에서 꺼내서(resolve) 사용한다.

 

 

 

1) 설치

npm i @fastify/awilix awilix

 

2) 플러그인 연결

 

 

fastify와 awilix를 연결해 주는 작업을 진행한다.

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

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

 

 

3) 컨테이너에 등록

 

 

컨테이너에 의존성 클래스들을 등록한다.

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(),
  }),
})

 

 

3-2) 클래스를 사용하여 등록

 

 

클래스를 사용하면 구조화 시켜 관리하기 편하다. 아래 예시는 싱글톤으로 설정하여 한 번만 생성되고 이후에 호출 될 경우 생성된 인스턴스를 사용하게 끔 해준다.

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(),
  }),
})

 

 

4) 컨테이너에서 꺼내서 사용

 

resolve를 이용하면 간단하게 꺼낼 수있다.

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

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

 

 

 

 

Reference

 

https://github.com/fastify/fastify-awilix

 

GitHub - fastify/fastify-awilix: Dependency injection support for fastify

Dependency injection support for fastify. Contribute to fastify/fastify-awilix development by creating an account on GitHub.

github.com

 

반응형

'Node.js' 카테고리의 다른 글

[Node JS] JS 의존성 주입 라이브러리 - tsyringe  (0) 2024.02.08
Comments