dev/nestjs

HTTP module

wlrn566 2023. 2. 13. 00:06

NestJs는 Axios가 내장된 HttpModule을 이용해서 HTTP 요청을 수행한다.

 

@nestjs/axios 설치

 

npm install @nestjs/axios axios

 

HttpModule을 import한다.

axios 옵션을 추가 할 수도 있다.  (옵션보기)

 

// test.module.ts
import { Module } from '@nestjs/common';
import { TestController } from './test.controller';
import { HttpModule } from '@nestjs/axios';

@Module({
  imports: [HttpModule],
  controllers: [TestController],
})
export class TestModule {}

// axios 옵션 추가
@Module({
  imports: [
    HttpModule.register({
      timeout: 5000,
      maxRedirects: 5,
    }),
  ],
  controllers: [TestController],
})

// registerAsync() 비동기
@Module({
  imports: [
    HttpModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        timeout: configService.get('HTTP_TIMEOUT'),
        maxRedirects: configService.get('HTTP_MAX_REDIRECTS'),
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [TestController],
})

 

생성자로 HttpService 를 주입한다.

 

 

// test.conroller.ts
import { HttpService } from '@nestjs/axios';
import { Controller } from '@nestjs/common';

@Controller('test')
export class TestController {
  constructor(private readonly httpService: HttpService) {}
}

 

반환값은 HttpService의 Observable이므로 rsjs의 firstValueFrom 또는 lastValueFrom을 사용한다.

 

import { HttpService } from '@nestjs/axios';
import { Controller, Get } from '@nestjs/common';
import { AxiosError } from 'axios';
import { catchError, firstValueFrom, lastValueFrom } from 'rxjs';

@Controller('test')
export class TestController {
  constructor(private readonly httpService: HttpService) {}

  @Get('axios')
  async findAll(): Promise<any> {
    const { data } = await firstValueFrom(
      this.httpService.get('https://jsonplaceholder.typicode.com/posts').pipe(
        catchError((error: AxiosError) => {
          console.log(error);
          throw 'An error happened!';
        }),
      ),
    );
    console.log(data);
    return data;
  }
}