minstudio

데코레이터 (Decorators) 기초와 활용

클래스와 그 멤버(메서드, 프로퍼티)를 수정하거나 메타데이터를 주입하는 특수한 문법(@)입니다. 프레임워크(NestJS, Angular 등)에서 매우 활발하게 사용되는 고급 메타 프로그래밍 기술입니다.

🎁 포장지 (Decorators) class MyService (기존 비즈니스 로직) @Injectable() 로직을 뜯어고치지 않고 외부에서 새로운 기능(메타데이터) 우아하게 덧붙임

🎁 포장지 (Decorators)

기존 코드의 내부 로직을 뜯어고치지 않고도,
마치 포장지로 감싸듯 외부에서 새로운 기능(로깅, 인증, 측정 등)을 우아하게 덧붙이는 마법입니다.

// 데코레이터를 사용하려면 tsconfig.json에서 
// "experimentalDecorators": true 설정이 필요합니다.

// 1. 클래스 데코레이터 팩토리 (인자를 받는 데코레이터)
function Controller(route: string) {
  return function (constructor: Function) {
    console.log(`[Controller Loaded] Route: ${route} for ${constructor.name}`);
  };
}

@Controller("/api/users")
class UserController {
  constructor() {}
}

// 2. 메서드 데코레이터 (실행 시간 측정기)
function LogTime() {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value; // 기존 메서드 보관
    
    // 기존 메서드 가로채기 (Override)
    descriptor.value = function (...args: any[]) {
      console.time(propertyKey);
      const result = originalMethod.apply(this, args);
      console.timeEnd(propertyKey);
      return result;
    };
  };
}

class Calculator {
  @LogTime() // 메서드 실행 시간을 자동으로 측정합니다.
  calculate() {
    for (let i = 0; i < 1000000; i++) {}
  }
}

new Calculator().calculate(); // calculate: 1.2ms
데코레이터 (Decorators) 기초와 활용 | Minstudio