개발이야기/Node&Nest

Nest.js + mssql 연동하기

Roslyn 2024. 1. 17. 13:38
반응형

이번에는 nest.js와 mssql 을 연동해 보자.

 

먼저 mssql 라이브러리를 설치해 준다.

npm install mssql

 

먼저 프로젝트에 Cors 이슈를 해결하기 위해 app에서 enableCors() 함수를 호출해 준다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = new DocumentBuilder()
    .setTitle('Your API Title')
    .setDescription('Your API Description')
    .setVersion('1.0')
    .addTag('nestjs-swagger-example') // optional
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  app.enableCors(); 
  await app.listen(3000);
}
bootstrap();

 

그 다음 app.service.ts 에 getServerDate 함수를 추가해 주자.

import { Injectable } from '@nestjs/common';
import * as sql from 'mssql';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }

  async getServerDate():Promise<any> {
    try
    {
      const pool = await new sql.ConnectionPool({
        user:"tester",
        password:"1q2w3e4r",
        server:"localhost",
        database:"Test",
        options: {
          TrustServerCertificate: true,
          encrypt: false,
        }
      }).connect();

      const result = await pool.query`Select getdate() as Today`;
      console.log('result : ', result);
      return result.recordset[0];
    }
    catch (e:any)
    {
      console.log('error : ', e);
      return e.message;
    }
  }
}

 

이제 컨트롤러에서 라우트를 잡아주면 끝.

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @Get("server")
  async getServerDate(): Promise<any> {
    let result = await this.appService.getServerDate();
    return result;
  }
}

 

이제 npm run start 로 서버를 실행시켜서 Swagger로 확인해 보자.

 

서버가 응답결과를 잘 반환하고 있음을 확인할 수 있다.

여기까지 Nest.js에서 MSSQL을 연동하는 가장 기본적인 방법을 알아보았다.

 

반응형