This commit is contained in:
dahyeon committed 2025-11-03 17:14:23 +00:00
commit 89eb5673c3
31 files changed
+13435

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
+12
View File
@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
+20
View File
@@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { GlobalModule } from './modules/global/global.module';
import { ArticleModule } from './modules/article/article.module';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: process.env.NODE_ENV === 'prod' ? '.env.prod' : process.env.NODE_ENV === 'test' ? '.env.test' : '.env.dev',
}),
GlobalModule,
ArticleModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+8
View File
@@ -0,0 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ArticleController } from './article.controller';
import { ArticleService } from './article.service';
describe('ArticleController', () => {
let controller: ArticleController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ArticleController],
providers: [ArticleService],
}).compile();
controller = module.get<ArticleController>(ArticleController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
+34
View File
@@ -0,0 +1,34 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { ArticleService } from './article.service';
import { CreateArticleDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';
@Controller('article')
export class ArticleController {
constructor(private readonly articleService: ArticleService) {}
@Post()
create(@Body() createArticleDto: CreateArticleDto) {
return this.articleService.create(createArticleDto);
}
@Get()
findAll() {
return this.articleService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.articleService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateArticleDto: UpdateArticleDto) {
return this.articleService.update(+id, updateArticleDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.articleService.remove(+id);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { ArticleService } from './article.service';
import { ArticleController } from './article.controller';
@Module({
controllers: [ArticleController],
providers: [ArticleService],
})
export class ArticleModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ArticleService } from './article.service';
describe('ArticleService', () => {
let service: ArticleService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ArticleService],
}).compile();
service = module.get<ArticleService>(ArticleService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
+26
View File
@@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { CreateArticleDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';
@Injectable()
export class ArticleService {
create(createArticleDto: CreateArticleDto) {
return 'This action adds a new article';
}
findAll() {
return `This action returns all article`;
}
findOne(id: number) {
return `This action returns a #${id} article`;
}
update(id: number, updateArticleDto: UpdateArticleDto) {
return `This action updates a #${id} article`;
}
remove(id: number) {
return `This action removes a #${id} article`;
}
}
@@ -0,0 +1 @@
export class CreateArticleDto {}
@@ -0,0 +1,4 @@
import { CreateArticleDto } from './create-article.dto';
export class UpdateArticleDto {}
@@ -0,0 +1 @@
export class Article {}
@@ -0,0 +1,36 @@
import { Injectable, OnModuleInit } from "@nestjs/common";
import { CosmosClient, Database, Container } from "@azure/cosmos";
import { SecretService } from "../secret/secret.service";
@Injectable()
export class CosmosDBService implements OnModuleInit {
constructor(
private readonly secretService: SecretService
) {
}
public async onModuleInit() {
await this.secretService.ready(); // 또는 첫 get에서 자동 대기
const endpoint = await this.secretService.get('COSMOSDB_ENDPOINT');
const key = await this.secretService.get('COSMOSDB_KEY');
const database = await this.secretService.get('COSMOSDB_DATABASE');
this.cosmosClient = new CosmosClient({
endpoint,
key,
});
this.database = this.cosmosClient.database(database);
this.articleContainer = this.database.container('article');
this.commentContainer = this.database.container('comment');
// console.log(this.cosmosClient, this.database, this.container);
}
public async getArticleList() {
const ex = await this.articleContainer.read();
console.log((await ex.container.items.query("SELECT * FROM article").fetchAll()));
}
private cosmosClient: CosmosClient;
private database: Database;
private articleContainer: Container;
private commentContainer: Container;
}
@@ -0,0 +1,10 @@
import { Module } from "@nestjs/common";
import { CosmosDBService } from "./cosmosdb.service";
@Module({
imports: [],
providers: [
CosmosDBService],
exports: [CosmosDBService],
})
export class DatabaseModule {}
+11
View File
@@ -0,0 +1,11 @@
import { Module, Global } from '@nestjs/common';
import { SecretModule } from './secret/secret.module';
import { DatabaseModule } from './database/database.module';
@Global()
@Module({
imports: [SecretModule, DatabaseModule],
providers: [],
exports: [SecretModule, DatabaseModule],
})
export class GlobalModule {}
@@ -0,0 +1,10 @@
import { Module } from "@nestjs/common";
import { SecretService } from "./secret.service";
@Module({
imports: [],
providers: [SecretService],
exports: [SecretService],
})
export class SecretModule {}
+117
View File
@@ -0,0 +1,117 @@
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",
// 필요시 추가
] 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;
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,
});
const res = await this.infisicalClient.secrets().listSecrets({
environment: "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();
}
}