Axios๋ ์์ญ ๊ฐ์ ์ ํ๋ฆฌ์ผ์ด์
์์ ๋๋ฆฌ ์ฌ์ฉ๋๋ ํ๋ถํ ๊ธฐ๋ฅ์ HTTP ํด๋ผ์ด์ธํธ์
๋๋ค. ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ Nest๋ ์ด ํจํค์ง๋ฅผ ๊ฐ์ธ์ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ด์ฅ๋ HttpModule๋ก ๊ณต๊ฐํฉ๋๋ค. HttpModule์ ๋จ์ํ HTTP ์์ฒญ์ ์ํํ๊ธฐ ์ํด Axios ๊ธฐ๋ฐ ๋ฉ์๋๋ฅผ ๋
ธ์ถํ๋ HttpService๋ฅผ ๋ด๋ณด๋ด๊ณ ๋ฆฌํด ์ ํ์ Observables๋ก ๋ณํํฉ๋๋ค.
HttpService๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด์๋ HttpModule์ ๊ฐ์ ธ์์ผํฉ๋๋ค.
@Module({
imports: [HttpModule],
providers: [CatsService],
})
export class CatsModule {}
info ํํธ HttpModule์ @nestjs/common ํจํค์ง์์ ๊ณต๊ฐ๋ฉ๋๋ค.
๊ทธ๋ฐ ๋ค์ HttpService๋ฅผ ์ฝ์
ํ ์ ์์ต๋๋ค. ์ด ํด๋์ค๋ @nestjs/common ํจํค์ง์์ ์ฝ๊ฒ ์ก์ธ์คํ ์ ์์ต๋๋ค.
@@filename()
@Injectable()
export class CatsService {
constructor(private readonly httpService: HttpService) {}
findAll(): Observable<AxiosResponse<Cat[]>> {
return this.httpService.get('http://localhost:3000/cats');
}
}
@@switch
@Injectable()
@Dependencies(HttpService)
export class CatsService {
constructor(httpService) {
this.httpService = httpService;
}
findAll() {
return this.httpService.get('http://localhost:3000/cats');
}
}
๋ชจ๋ ๋ฉ์๋๋ Observable ์ค๋ธ์ ํธ๋ก ๋ฉํ๋ AxiosResponse๋ฅผ ๋ฆฌํดํฉ๋๋ค.
Axios๋ HttpService๋ฅผ ๋์ฑ ๊ฐ๋ ฅํ๊ฒ ๋ง๋ค๊ธฐ ์ํด ํ์ฉํ ์ ์๋ ๋ง์ ์ต์
์ ์ ๊ณตํฉ๋๋ค. ์ฌ๊ธฐ์ ๋ํด ์์ธํ ์์๋ณด์ญ์์ค. ๊ธฐ๋ณธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ธ์คํด์ค๋ฅผ ๊ตฌ์ฑํ๋ ค๋ฉด HttpModule์ register()๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ญ์์ค.
์ด๋ฌํ ๋ชจ๋ ์์ฑ์ axios ์์ฑ์๋ก ์ ๋ฌ๋ฉ๋๋ค.
Async configuration
๋ชจ๋ ์ต์
์ ๋ฏธ๋ฆฌ ์ ๋ฌํ๋ ๋์ ๋น๋๊ธฐ์์ผ๋ก ์ ๋ฌํ๋ ค๋ ๊ฒฝ์ฐ๊ฐ ์ข
์ข
์์ต๋๋ค. ์ด ๊ฒฝ์ฐ, ๋น๋๊ธฐ ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํ๋ ๋ค์ํ ๋ฐฉ๋ฒ์ ์ ๊ณตํ๋ registerAsync() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ญ์์ค.
๊ฐ๋ฅํ ์ฒซ ๋ฒ์งธ ๋ฐฉ๋ฒ์ ํฉํ ๋ฆฌ ๊ธฐ๋ฅ์ ์ฌ์ฉํ๋ ๊ฒ์
๋๋ค.
๋ถ๋ช
ํ, ์ฐ๋ฆฌ ํฉํ ๋ฆฌ๋ ๋ค๋ฅธ ๋ชจ๋ ๊ฒ์ฒ๋ผ ํ๋ํฉ๋๋ค ( async์ผ ์๋ ์๊ณ inject์ ํตํด ์์กด์ฑ์ ์ฃผ์
ํ ์๋ ์์ต๋๋ค).
๋๋ ํฉํ ๋ฆฌ ๋์ ํด๋์ค๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
์์ ๊ตฌ์ฑ์ HttpModule๋ด์์ HttpConfigService๋ฅผ ์ธ์คํด์คํ ํ๊ณ ์ต์
๊ฐ์ฒด๋ฅผ ๋ง๋๋ ๋ฐ ํ์ฉํฉ๋๋ค. HttpConfigService๋ HttpModuleOptionsFactory ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํด์ผํฉ๋๋ค.
HttpModule ๋ด๋ถ์ HttpConfigService๊ฐ ์์ฑ๋๋ ๊ฒ์ ๋ฐฉ์งํ๊ณ ๋ค๋ฅธ ๋ชจ๋์์ ๊ฐ์ ธ์จ ๊ณต๊ธ์๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด useExisting ๊ตฌ๋ฌธ์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
HttpModule์ ๊ฐ์ ธ์จ ๋ชจ๋์ ๊ฒ์ํ์ฌ ์์ฒด์ ์ผ๋ก ์ธ์คํด์คํํ๋ ๋์ ์ด๋ฏธ ์์ฑ๋ ConfigService๋ฅผ ์ฌ์ฌ์ฉํฉ๋๋ค.