프론트엔드 작업을 시작할 때 가장 첫 출발점이 뭐냐고 묻는다면 OpenAPI spec으로부터 클라이언트 코드를 생성하는 것이라 하겠다.
OpenAPI(swagger) 사양은 일반적으로 아래의 형식으로 접근할 수 있다. 물론 백엔드의 설정에 따라 달라질 수 있다.
%URL%/v3/api-docs
위의 URL을 아래의 Swagger Editor에 import하면 Swagger UI 형태의 API 목록과 데이터 스키마를 볼 수 있다.

여기에서 Generate Client 항목을 눌러 자신의 개발 환경에 맞는 클라이언트 코드를 생성할 수 있다.
이 방법을 활용해 RESTful API 연동 개발 시 반복 작업을 줄이고 API 표준 부합성을 보장할 수 있다.
오늘 하고 싶은 얘기는 여기서 생성된 클라이언트 중 typescript-angular의 API base path를 설정하는 방법이다.
API가 업데이트 될 때마다 클라이언트를 재생성해야 하는데 base_path가 딱 박혀져서 나와 매번 수정을 해줘야 하는게 문제였다.
이 반복 작업을 없애기 위해 Angular의 dependency injection system을 이용해 해결해보자.
먼저 typescript-angular로 생성된 client 코드의 압축을 풀어보면 아래 형식의 variables.ts 파일이 root folder에 존재할 것이다.
import { InjectionToken } from '@angular/core';
export const BASE_PATH = new InjectionToken<string>('BASE_PATH');
더불어 확인해야 할 것이 생성된 서비스들이 아래 형식과 같이 BASE_PATH 변수 injection을 구현해놨는지 여부이다.
import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BASE_PATH } from './variables';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient,
@Inject(BASE_PATH) private basePath: string) {
console.log('Base Path:', this.basePath);
}
// Example method using the basePath
getItems() {
return this.http.get(`${this.basePath}/items`);
}
}
구현이 되어 있다면 AppModule.ts에서 아래와 같이 BASE_PATH 값을 주입해보자. 아래 예제의 경우엔 환경 변수(apiUrl)를 활용하였다.
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BASE_PATH } from './backend-api/sample-api/variables';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent
],
imports: [
AppRoutingModule,
],
providers: [
{
provide: BASE_PATH,
useValue: environment.apiUrl
},
],
bootstrap: [AppComponent]
})
export class AppModule { }
이제 Client 코드가 업데이트 되어도 동일한 BASE_PATH를 주입할 수 있다.
'IT 교양' 카테고리의 다른 글
Domain-Driven Design: 도메인 주도 설계 (0) | 2025.02.21 |
---|---|
eBook은 어떻게 동작할까? (1) | 2025.01.22 |
Actor Model에 대하여 (1) | 2025.01.07 |
북유럽 나라들이 오픈소스 소프트웨어 강국인 이유 (0) | 2024.08.26 |
Command-query separation (명령 질의 분리) (0) | 2024.08.06 |