first commit

This commit is contained in:
dahyeon committed 2025-11-07 09:17:35 +09:00
commit 02255d7240
36 files changed
+13591

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
import { Module, Global } from '@nestjs/common';
import { SecretModule } from './secret/secret.module';
import { DatabaseModule } from './database/database.module';
import { NatsModule } from './nats/nats.module';
@Global()
@Module({
imports: [SecretModule, NatsModule],
providers: [],
exports: [SecretModule, NatsModule],
})
export class GlobalModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Module } from "@nestjs/common";
import { NatsService } from "./nats.service";
@Module({
providers: [NatsService],
exports: [NatsService],
})
export class NatsModule {}
+49
View File
@@ -0,0 +1,49 @@
import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
import { NatsConnection, connect } from "nats";
import { SecretService } from "../secret/secret.service";
import fs from "fs/promises";
@Injectable()
export class NatsService implements OnModuleInit, OnModuleDestroy {
private natsClient: NatsConnection;
private endpoint: string;
private user: string;
private password: string;
constructor(
private readonly secretService: SecretService
) {}
async onModuleInit() {
await this.secretService.ready();
this.endpoint = await this.secretService.get("NATS_ENDPOINT");
this.user = await this.secretService.get("NATS_USER");
this.password = await this.secretService.get("NATS_PASS");
// console.log(this.endpoint)
const cacert = (await fs.readFile("internal-service-ca.pem")).toString()
this.natsClient = await connect({
servers: [this.endpoint],
tls: {
ca: cacert,
},
authenticator: () => {
return {
user: this.user,
pass: this.password
}
}
});
// const result = await this.natsClient.status();
// console.log(result)
}
async onModuleDestroy() {
const done = this.natsClient.closed();
await this.natsClient.close();
const err = await done;
if (err) {
console.log(`error closing:`, err);
}
}
}
@@ -0,0 +1,10 @@
import { Module } from "@nestjs/common";
import { SecretService } from "./secret.service";
@Module({
imports: [],
providers: [SecretService],
exports: [SecretService],
})
export class SecretModule {}
+122
View File
@@ -0,0 +1,122 @@
import { Injectable, Logger } from "@nestjs/common";
import { InfisicalSDK } from "@infisical/sdk";
import { ConfigService } from "@nestjs/config";
type SecretMap = Record<string, string | boolean | undefined>;
@Injectable()
export class SecretService {
private logger = new Logger(SecretService.name);
private secrets: SecretMap | null = null; // null = 아직 로드 전
private loading?: Promise<void>; // 진행 중인 로드(중복 호출 방지)
private infisicalClient: InfisicalSDK;
private readonly siteUrl: string;
private readonly clientSecret: string;
private readonly clientId: string;
private readonly projectId: string;
private readonly PROCESS_ENVS = [
"COSMOSDB_ENDPOINT",
"COSMOSDB_KEY",
"NATS_ENDPOINT",
"NATS_TOKEN",
"NATS_URL",
// 필요시 추가
] as const;
constructor(private readonly config: ConfigService) {
this.siteUrl = this.config.get<string>("INFISICAL_SITE_URL") ?? "https://secret-manager.dahyeon.us/";
this.clientSecret = this.config.get<string>("INFISICAL_CLIENT_SECRET") as string;
this.clientId = this.config.get<string>("INFISICAL_CLIENT_ID") as string;
this.projectId = this.config.get<string>("INFISICAL_PROJECT_ID") as string;
// console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId)
if (!this.siteUrl || !this.clientSecret || !this.clientId) {
throw new Error("Missing required Infisical configuration");
}
this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl });
}
/** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */
private async fetchSecrets(): Promise<void> {
if (this.secrets) return; // 이미 로드됨
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
this.loading = (async () => {
await this.infisicalClient.auth().universalAuth.login({
clientId: this.clientId,
clientSecret: this.clientSecret,
});
// console.log(this.infisicalClient)
const res = await this.infisicalClient.secrets().listSecrets({
environment: process.env.NODE_ENV === 'prod' ? 'prod' : process.env.NODE_ENV === 'test' ? 'staging' : 'dev',
projectId: this.projectId,
});
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
const map: SecretMap = {};
for (const s of res.secrets) {
map[s.secretKey] = s.secretValue;
}
// 필요한 값은 process.env에 반영
for (const k of this.PROCESS_ENVS) {
const v = map[k as string];
if (typeof v === "string" && v.length > 0) {
process.env[k as string] = v;
}
}
this.secrets = map;
this.logger.log(`Fetched ${Object.keys(map).length} secrets from Infisical`);
})();
try {
await this.loading;
} finally {
this.loading = undefined; // 실패/성공 모두 끝나면 해제(실패 시 재시도 가능)
}
}
/** lazy get: 필요할 때 처음 한번만 로드 */
public async get<T = string>(key: string, fallback?: T): Promise<T> {
if (!this.secrets) {
await this.fetchSecrets();
}
const val = this.secrets![key];
if (val === undefined) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`Secret not found for key="${key}"`);
}
return val as T;
}
/** 필요 시: 동기 접근(초기화 안됐으면 에러). constructor 등에서 강제 사용 금지 */
public getSync<T = string>(key: string, fallback?: T): T {
if (!this.secrets) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`SecretService not initialized yet (key="${key}")`);
}
const val = this.secrets[key];
if (val === undefined) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`Secret not found for key="${key}"`);
}
return val as T;
}
/** 선택: 사전에 강제로 로드하고 싶을 때 호출 */
public async ready(): Promise<void> {
await this.fetchSecrets();
}
}
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ImageController } from './image.controller';
import { ImageService } from './image.service';
describe('ImageController', () => {
let controller: ImageController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ImageController],
providers: [ImageService],
}).compile();
controller = module.get<ImageController>(ImageController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
+7
View File
@@ -0,0 +1,7 @@
import { Controller } from '@nestjs/common';
import { ImageService } from './image.service';
@Controller('image')
export class ImageController {
constructor(private readonly imageService: ImageService) {}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { ImageService } from './image.service';
import { ImageController } from './image.controller';
@Module({
controllers: [ImageController],
providers: [ImageService],
})
export class ImageModule {}
+18
View File
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ImageService } from './image.service';
describe('ImageService', () => {
let service: ImageService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ImageService],
}).compile();
service = module.get<ImageService>(ImageService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
+4
View File
@@ -0,0 +1,4 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class ImageService {}