A lightweight Config Client compatible with Spring Cloud Config Server
npm install @tjdrbs205/config-clientSpring Cloud Config 호환 서버를 위한 경량 TypeScript 클라이언트 라이브러리입니다.
- Spring Cloud Config 호환 - Spring Cloud Config Server와 완벽 호환
- TypeScript 지원 - 완전한 타입 정의 제공
- 다양한 응답 형식 - JSON, YAML, Properties 형식 지원
- 자동 재시도 - 네트워크 오류 시 지수 백오프 재시도
- 인증 지원 - API Key 인증 지원
- 경량화 - 외부 의존성 없음 (Node.js 18+ native fetch 사용)
---
``bash`
npm install @tjdrbs205/config-client
---
`typescript
import { createClient } from "@tjdrbs205/config-client";
const client = createClient({
endpoint: "http://localhost:8000",
application: "my-app",
profiles: ["dev"],
});
const config = await client.load();
// 설정 값 조회
const dbHost = config.get
const dbPort = config.get
// 전체 설정 객체
console.log(config.toObject());
`
`typescript
// API Key 인증 (Production 모드)
const client = createClient({
endpoint: "http://localhost:8000",
application: "my-app",
profiles: ["prod"],
auth: {
apiKey: "your-api-key",
},
});
// 다중 애플리케이션 설정 로드 (병합)
const client = createClient({
endpoint: "http://localhost:8000",
application: ["common-config", "my-app"], // common-config + my-app 병합 (my-app 우선)
profiles: ["dev"],
});
`
---
ConfigClient 인스턴스를 생성합니다.
#### 옵션
| 옵션 | 타입 | 필수 | 기본값 | 설명 |
| ------------- | ------------------------ | ---- | ------------- | -------------------------------- |
| endpoint | string | ✅ | - | Config Server URL |application
| | string \| string[] | ✅ | - | 애플리케이션 이름 (배열 시 병합) |profiles
| | string[] | ❌ | ['default'] | 프로파일 목록 |label
| | string | ❌ | 'main' | Git 브랜치/레이블 |auth
| | AuthOptions | ❌ | - | 인증 옵션 |timeout
| | number | ❌ | 5000 | 요청 타임아웃 (ms) |headers
| | Record | ❌ | {} | 추가 HTTP 헤더 |retry
| | RetryOptions | ❌ | - | 재시도 옵션 |
#### AuthOptions
| 옵션 | 타입 | 설명 |
| -------- | -------- | ------------ |
| apiKey | string | API Key 인증 |
#### RetryOptions
| 옵션 | 타입 | 기본값 | 설명 |
| -------------------- | --------- | ------ | ---------------- |
| maxRetries | number | 3 | 최대 재시도 횟수 |retryDelay
| | number | 1000 | 재시도 간격 (ms) |exponentialBackoff
| | boolean | true | 지수 백오프 사용 |
---
#### load(): Promise
설정을 로드하고 Config 래퍼 객체를 반환합니다.
`typescript`
const config = await client.load();
#### loadAsYaml(): Promise
YAML 형식으로 설정을 로드합니다.
`typescript`
const yaml = await client.loadAsYaml();
#### loadAsProperties(): Promise
Properties 형식으로 설정을 로드합니다.
`typescript`
const props = await client.loadAsProperties();
#### loadAsJson(): Promise
중첩 JSON 형식으로 설정을 로드합니다.
`typescript`
const json = await client.loadAsJson();
#### healthCheck(): Promise
서버 상태를 확인합니다.
`typescript`
const isHealthy = await client.healthCheck();
---
#### get
점(.) 표기법으로 설정 값을 조회합니다.
`typescript`
const host = config.get
const port = config.get
#### has(key: string): boolean
설정 키 존재 여부를 확인합니다.
`typescript`
if (config.has("database.password")) {
// ...
}
#### toObject(): Record
중첩 객체 형태로 반환합니다.
`typescript`
const obj = config.toObject();
// { database: { host: 'localhost', port: 5432 } }
#### toFlatObject(): Record
평면화된 객체로 반환합니다.
`typescript`
const flat = config.toFlatObject();
// { 'database.host': 'localhost', 'database.port': 5432 }
#### forEach(callback: (value, key) => void): void
모든 설정에 대해 콜백을 실행합니다.
`typescript${key}: ${value}
config.forEach((value, key) => {
console.log();`
});
#### 속성
| 속성 | 타입 | 설명 |
| ------------ | ------------------------- | ----------------------- |
| raw | ConfigResponse | 원본 응답 데이터 |properties
| | Record | 병합된 설정 (중첩 객체) |name
| | string | 애플리케이션 이름 |profiles
| | string[] | 활성 프로파일 |label
| | string \| null | Git 레이블 |version
| | string \| null | Git 커밋 버전 |
---
`typescript
import { createClient, ConfigClientError } from "@tjdrbs205/config-client";
try {
const config = await client.load();
} catch (error) {
if (error instanceof ConfigClientError) {
console.error(Config 로드 실패: ${error.message});상태 코드: ${error.statusCode}
console.error();엔드포인트: ${error.endpoint}
console.error();`
}
}
---
`javascript
const { createClient } = require("@tjdrbs205/config-client");
async function loadConfig() {
const client = createClient({
endpoint: process.env.CONFIG_SERVER_URL,
application: "my-app",
profiles: [process.env.NODE_ENV || "dev"],
});
return client.load();
}
`
`typescript
import { createClient } from "@tjdrbs205/config-client";
const config = await createClient({
endpoint: "http://config-server:8000",
application: "my-app",
profiles: ["prod"],
auth: { apiKey: process.env.CONFIG_API_KEY },
}).load();
`
`typescript
import { ConfigModule } from "@nestjs/config";
import { createClient } from "@tjdrbs205/config-client";
@Module({
imports: [
ConfigModule.forRoot({
load: [
async () => {
const client = createClient({
endpoint: process.env.CONFIG_SERVER_URL,
application: "nestjs-app",
profiles: [process.env.NODE_ENV],
});
const config = await client.load();
return config.toObject();
},
],
}),
],
})
export class AppModule {}
``
---
- Node.js 18.0.0 이상 (native fetch 사용)
---
MIT