NestJS를 활용한 자바스크립트 백엔드 애플리케이션의 화면 템플릿화

NestJS는 JavaScript 백엔드 애플리케이션을 개발하기 위한 프레임워크로서, Angular와 비슷한 구조와 패턴을 사용하여 모듈화된 애플리케이션 개발을 가능하게 합니다. NestJS는 기본적으로 JSON API를 반환하는 RESTful 서비스를 만들기 위해 설계되었지만, 때로는 웹페이지를 구성하는데 사용되는 화면 템플릿이 필요할 수도 있습니다.

화면 템플릿을 구현하기 위해 NestJS에서는 여러 가지 옵션이 있습니다. 그 중 하나는 Pug와 같은 템플릿 엔진을 사용하는 것입니다. Pug는 간결하고 가독성이 높은 문법으로 템플릿을 작성할 수 있도록 도와줍니다.

먼저, NestJS에서 Pug를 사용하려면 다음 단계를 따라야 합니다:

1. Pug 패키지 설치

NestJS 프로젝트의 루트 디렉토리에서 다음 명령을 실행하여 Pug 패키지를 설치합니다:

$ npm install --save @nestjs/pug pug

2. AppModule 설정

프로젝트의 AppModule에서 PugModule을 import합니다. 예를 들어, 다음과 같이 AppModule의 imports 배열에 추가할 수 있습니다:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PugModule } from '@nestjs/pug';

@Module({
  imports: [PugModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

3. Pug 컨트롤러 생성 및 라우트 설정

Pug 컨트롤러를 생성하고 원하는 라우트를 설정합니다. PugController를 생성하고, @Controller() 데코레이터를 사용하여 컨트롤러를 선언합니다:

import { Controller, Get } from '@nestjs/common';
import { PugService } from './pug.service';

@Controller('pug')
export class PugController {
  constructor(private readonly pugService: PugService) {}

  @Get()
  async getExamplePugTemplate() {
    const data = await this.pugService.getData();
    return { data };
  }
}

4. Pug 서비스 생성

Pug 서비스를 생성하여 Pug 컨트롤러에서 사용할 데이터를 가져옵니다. PugService를 생성하고, 필요한 데이터를 가져오는 메서드를 구현합니다:

import { Injectable } from '@nestjs/common';

@Injectable()
export class PugService {
  async getData() {
    // 데이터 가져오기 로직 구현
    return 'Example Data';
  }
}

5. Pug 템플릿 작성

src/views 디렉토리 내에 Pug 템플릿 파일을 작성합니다. 예를 들어, example.pug라는 파일을 생성하고 다음과 같이 작성할 수 있습니다:

html
  head
    title Example Pug Template

  body
    h1 Hello, Pug!
    p= data

6. 컨트롤러에서 템플릿 렌더링

Pug 컨트롤러에서 데이터를 가져오고 PugService를 통해 템플릿을 렌더링합니다. getExamplePugTemplate 메서드를 다음과 같이 수정하여 Pug 템플릿을 렌더링하고 응답합니다:

@Get()
async getExamplePugTemplate() {
  const data = await this.pugService.getData();
  return this.pugService.render('example', { data });
}

위와 같이 PugService에 render 메서드를 만들어 템플릿 파일 이름과 데이터를 전달하면 템플릿이 렌더링되고 HTML로 변환됩니다.

이제 NestJS를 통해 화면 템플릿화를 쉽게 구현할 수 있습니다. Pug를 사용하면 간결하고 가독성이 높은 템플릿을 작성할 수 있으며, NestJS의 모듈화된 구조와 함께 사용하면 효율적인 애플리케이션 개발이 가능합니다.

참고 자료: NestJS 공식 문서