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

[Node JS] JS 의존성 주입 라이브러리 - tsyringe 본문

Node.js

[Node JS] JS 의존성 주입 라이브러리 - tsyringe

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

 

 

JS로 벡엔드를 개발할 때 DI를 어떻게 설계 해야할 지 고민이 될 것이다. 이 때 tsyringe는 좋은 선택이다.

 


 

 

 

JS 의존성 주입 라이브러리로 tsyringe는 코드 관리에 아주 좋다. 왜냐하면 다른 라이브러리에 비해 코드의 양이 매우 짧다. 그 이유는 이 라이브러리는 의존성을 데코레이터 기반으로 Container에 등록 해주는 방식인데 클래스에 데코레이터가 붙어있으면 자동 으로 container에 등록해주기 때문에 코드의 양이 줄어든다. ( 마치 스프링 같다. )

 

 

그럼 사용하는 방법에 대해 코드로 알아보자

 

 

1) 설치 방법

// npm
npm install --save tsyringe

// pnpm
pnpm add tsyringe

// yarn
yarn add tsyringe

 

2) tsconfig.json 설정

 

데코레이터 관련 설정을 tsconfig.json 에 추가 해야 한다.

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

 

3) reflect-metadata 전역 설정

 

한 번만 설정해주면 된다. index.ts에 설정해주자.

// index.ts
import "reflect-metadata";

 

 

4) 데이터 베이스 설정

DBConfig를 Container에 등록한다.

@singleton
export class DBConfig implements Disposable {
	
	// db 관련 변수

  constructor() {
		// db 연결  
	}
	
	get db(){
    // db 관련 변수 getter
	}

	dispose() {
	  // dispose 로직
  }
}

 

5) 의존성 주입: Foo <- DBConfig

 

추가적으로 Foo도 container에 등록되어서 resolve를 통해 Foo에 접근할 수있다.

import {injectable} from "tsyringe";

@singleton
class Foo {
  constructor(private database: DBConfig) {}
}

// some other file
import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";

const instance = container.resolve(Foo);

 

 

이런 방식으로 사용하면 된다. 아주 간단하다.

더 다양한 활용은 공식 문서를 참고하자.

 

 

 

Reference

https://github.com/microsoft/tsyringe

 

GitHub - microsoft/tsyringe: Lightweight dependency injection container for JavaScript/TypeScript

Lightweight dependency injection container for JavaScript/TypeScript - GitHub - microsoft/tsyringe: Lightweight dependency injection container for JavaScript/TypeScript

github.com

 

반응형
Comments