initial commit

This commit is contained in:
dahyeon committed 2026-04-11 11:44:55 -07:00
commit e3da5d83b6
49 files changed
+10011

No files matched your search

@@ -0,0 +1,94 @@
import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose';
import { SecretService } from '../secret/secret.service';
import { moeumModelDefinitions, MoeumModelTypes } from './schema';
@Injectable({ scope: Scope.DEFAULT })
export class ConnectionService implements OnModuleInit {
private connection: mongoose.Connection | null = null;
constructor(private readonly secretService: SecretService) {}
private moeumModels: Map<string, mongoose.Model<any>> | null = null;
public async getConnection(): Promise<mongoose.Connection> {
if (this.connection !== null && this.connection.readyState === 1) {
return this.connection;
}
const connectionString = await this.secretService.get(
'MONGODB_CONNECTION_STRING',
);
const defaultConnection = await mongoose
.createConnection(connectionString, {
dbName: 'moeum',
minPoolSize: 10,
maxPoolSize: 20,
})
.asPromise();
this.connection = defaultConnection;
console.log('Default Connection이 새로 생성됨.');
return this.connection;
}
public async getMoeumModels<K extends keyof MoeumModelTypes>(
modelKey: K,
): Promise<mongoose.Model<MoeumModelTypes[K]>> {
if (this.moeumModels)
return this.moeumModels.get(modelKey) as mongoose.Model<
MoeumModelTypes[K]
>;
const moeumModels = new Map<K, mongoose.Model<MoeumModelTypes[K]>>();
// const connection = await this.getTenantConnection(tenantId);
const connection = await this.getConnection();
moeumModelDefinitions.forEach((modelDefinition) => {
// 이미 생성된 경우 컴파일 스킵.
if (
Object.prototype.hasOwnProperty.call(
connection.models,
modelDefinition.name,
)
) {
moeumModels.set(
modelDefinition.name as K,
connection.models[modelDefinition.name],
);
return;
} else {
moeumModels.set(
modelDefinition.name as K,
connection.model<MoeumModelTypes[K]>(
modelDefinition.name,
modelDefinition.schema,
modelDefinition.schemaName,
),
);
}
});
this.moeumModels = moeumModels;
return moeumModels.get(modelKey) as mongoose.Model<MoeumModelTypes[K]>;
}
public async createSession(
options?: mongoose.ClientSessionOptions,
): Promise<mongoose.ClientSession | undefined> {
try {
const connection = await this.getConnection();
const session = await connection.startSession(options);
return session as unknown as mongoose.ClientSession;
} catch (error) {
console.log(error);
}
}
public async onModuleInit() {
await this.getConnection().catch(console.error);
}
public async onModuleDestroy() {
this.connection?.close();
}
}
@@ -0,0 +1,9 @@
import { DynamicModule, Module } from '@nestjs/common';
import { ConnectionService } from './connection.service';
@Module({
imports: [],
providers: [ConnectionService],
exports: [ConnectionService],
})
export class DatabaseModule {}
@@ -0,0 +1,248 @@
import mongoose, { Schema, HydratedDocument } from 'mongoose';
import { ModelDefinition } from './types';
export type MetadataDataType =
| 'string'
| 'number'
| 'boolean'
| 'array'
| 'json';
export type MetadataValue =
| string
| number
| boolean
| unknown[]
| Record<string, unknown>
| null;
export interface MongooseTimestamps {
createdAt: Date;
updatedAt: Date;
}
export interface Metadata {
key: string;
value: MetadataValue;
dataType: MetadataDataType;
isReserved: boolean;
}
export interface TaxonomyChildItem {
title: string;
order: number;
articleId?: mongoose.Types.ObjectId;
slug?: string; //article document의 slug 참조 (임베딩)
children?: TaxonomyChildItem[];
}
export interface Taxonomy extends MongooseTimestamps {
label: string;
items: TaxonomyChildItem[];
metadatas: Metadata[];
}
export type TaxonomyDocument = HydratedDocument<Taxonomy>;
export interface ContentSection {
headline: string;
taxonomies: ContentSectionEmbeddedTaxonomy[];
}
export interface ContentSectionEmbeddedTaxonomy {
taxonomyId: mongoose.Types.ObjectId;
label: string; // 성능 최적화를 위해 임베딩된 label
}
export interface Content extends MongooseTimestamps {
key: string;
label: string;
sections: ContentSection[];
}
export type ContentDocument = HydratedDocument<Content>;
export interface Article extends MongooseTimestamps {
title: string;
slug: string;
content: string;
status: 'draft' | 'published' | 'archived';
metadatas: Metadata[];
}
export type ArticleDocument = HydratedDocument<Article>;
const metadataValueDefinition =
{
type: mongoose.SchemaTypes.Mixed,
required: false, // required: true로 하면 value가 null인 경우 에러 발생
default: null,
validate: {
validator: function (this: Metadata, v: MetadataValue) {
if (v === null) {
return true;
}
switch (this.dataType) {
case 'string':
return typeof v === 'string';
case 'number':
return typeof v === 'number';
case 'boolean':
return typeof v === 'boolean';
case 'array':
return Array.isArray(v);
case 'json':
return typeof v === 'object' && !Array.isArray(v);
default:
return false;
}
},
message: function (this: Metadata, props: { value: MetadataValue }) {
return `Value "${props.value}" does not match the expected data type "${this.dataType}" for key "${this.key}".`;
},
},
} as mongoose.SchemaDefinitionProperty<MetadataValue>;
export const MetadataSubSchema = new mongoose.Schema<Metadata>(
{
key: { type: String, required: true },
value: metadataValueDefinition,
dataType: {
type: String,
required: false,
default: 'string',
enum: ['string', 'number', 'boolean', 'array', 'json'],
},
isReserved: { type: Boolean, required: false, default: false },
},
{
_id: false,
},
);
export const TaxonomyChildItemSubSchema = new Schema<TaxonomyChildItem>(
{
title: { type: String, required: true },
order: { type: Number, required: true, default: 100 },
slug: { type: String }, // slug는 없을 수도 있으므로 required 제외
articleId: { type: Schema.Types.ObjectId, ref: 'article' },
},
{
_id: false, // 하위 아이템마다 _id가 생성되는 것을 방지 (선택 사항)
},
);
// **중요: 재귀 참조 설정**
// 스키마 정의 후 .add()를 통해 자기 자신을 children 배열로 추가합니다.
TaxonomyChildItemSubSchema.add({
children: { type: [TaxonomyChildItemSubSchema], default: [] },
});
// 2. 메인 도큐먼트 스키마 (Root)
export const TaxonomySchema = new Schema<Taxonomy>(
{
// items 배열은 위에서 정의한 재귀 스키마를 따름
label: { type: String, required: true },
items: {
type: [TaxonomyChildItemSubSchema],
default: [],
},
// metadata는 구조가 가변적이므로 Mixed 타입 사용
metadatas: {
type: [MetadataSubSchema],
required: true,
default: [],
},
},
{
timestamps: true, // createAt, updatedAt 자동 생성
collection: 'taxonomy', // 컬렉션 이름 지정
},
);
TaxonomySchema.index({ label: 1 }, { unique: true });
export const ContentSectionEmbeddedTaxonomySubSchema =
new Schema<ContentSectionEmbeddedTaxonomy>(
{
taxonomyId: {
type: Schema.Types.ObjectId,
ref: 'taxonomy',
required: true,
},
label: { type: String, required: true },
},
{ _id: false },
);
export const ContentSectionSubSchema = new Schema<ContentSection>(
{
headline: { type: String, required: true },
taxonomies: {
type: [ContentSectionEmbeddedTaxonomySubSchema],
required: true,
default: [],
},
},
{ _id: false },
);
export const ContentSchema = new Schema<Content>(
{
key: { type: String, required: true, unique: true },
label: { type: String, required: true },
sections: {
type: [ContentSectionSubSchema],
default: [],
},
},
{
timestamps: true,
collection: 'content',
},
);
export const ArticleSchema = new Schema<Article>(
{
title: { type: String, required: true },
content: { type: String, required: true },
slug: { type: String, required: true, unique: true },
status: {
type: String,
enum: ['draft', 'published', 'archived'],
default: 'draft',
},
metadatas: {
type: [MetadataSubSchema],
required: true,
default: [],
validate: {
validator: function (metas: Metadata[]) {
const keys = metas.map((m) => m.key);
return keys.length === new Set(keys).size;
},
message: 'Duplicate metadata keys are not allowed.',
},
},
},
{
timestamps: true,
collection: 'article',
},
);
ArticleSchema.index({ title: 'text', content: 'text' });
export const moeumModelDefinitions: ModelDefinition[] = [
{ name: 'taxonomy', schema: TaxonomySchema, schemaName: 'taxonomy' },
{ name: 'content', schema: ContentSchema, schemaName: 'content' },
{ name: 'article', schema: ArticleSchema, schemaName: 'article' },
];
export interface MoeumModelTypes {
taxonomy: Taxonomy;
content: Content;
article: Article;
}
+5
View File
@@ -0,0 +1,5 @@
export interface ModelDefinition {
name: string;
schema: mongoose.Schema<any>;
schemaName?: string;
}
@@ -0,0 +1,14 @@
import { Module, Global } from '@nestjs/common';
import { SecretModule } from './secret/secret.module';
// import { DatabaseModule } from './database/database.module';
import { NatsModule } from './nats/nats.module';
import { DatabaseModule } from './database/database.module';
// import { DatabaseModule } from './database/database.module';
@Global()
@Module({
imports: [SecretModule, NatsModule, DatabaseModule],
providers: [],
exports: [SecretModule, NatsModule, DatabaseModule],
})
export class GlobalModule {}
@@ -0,0 +1 @@
export const NATS_CLIENT = Symbol('NATS_CLIENT');
@@ -0,0 +1,50 @@
import { Module } from '@nestjs/common';
import fs from 'fs/promises';
import { connect } from 'nats';
import type { NatsConnection } from 'nats';
import { SecretModule } from '../secret/secret.module';
import { SecretService } from '../secret/secret.service';
import { NATS_CLIENT } from './nats.constants';
import { NatsService } from './nats.service';
@Module({
imports: [SecretModule],
providers: [
{
provide: NATS_CLIENT,
inject: [SecretService],
useFactory: async (
secretService: SecretService,
): Promise<NatsConnection> => {
await secretService.ready();
const [endpoint, user, password, serviceName, cacert] =
await Promise.all([
secretService.get<string>('NATS_ENDPOINT'),
secretService.get<string>('NATS_USER'),
secretService.get<string>('NATS_PASS'),
secretService.get<string>('SERVICE_NAME'),
fs.readFile('internal-service-ca.pem', 'utf8'),
]);
return connect({
name: serviceName,
servers: [endpoint],
tls: {
ca: cacert,
},
maxReconnectAttempts: -1,
reconnectTimeWait: 500,
reconnect: true,
pingInterval: 20000,
timeout: 5000,
user,
pass: password,
});
},
},
NatsService,
],
exports: [NatsService, NATS_CLIENT],
})
export class NatsModule {}
@@ -0,0 +1,36 @@
import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
import { StringCodec } from 'nats';
import type { NatsConnection } from 'nats';
import { NATS_CLIENT } from './nats.constants';
@Injectable()
export class NatsService implements OnModuleDestroy {
private readonly stringCodec = StringCodec();
constructor(
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
) {}
async onModuleDestroy() {
try {
// 안전 종료: drain -> closed 대기
const closed = this.natsClient.closed();
await this.natsClient.drain();
const err = await closed;
if (err) console.error('NATS closed with error:', err);
} catch (e) {
// drain 실패 시 강제 close
try {
await this.natsClient.close();
} catch {}
}
}
public async publish<T = unknown>(subject: string, data: T): Promise<void> {
this.natsClient.publish(
subject,
this.stringCodec.encode(JSON.stringify(data)),
);
await this.natsClient.flush();
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { SecretService } from './secret.service';
@Module({
imports: [],
providers: [SecretService],
exports: [SecretService],
})
export class SecretModule {}
@@ -0,0 +1,134 @@
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();
}
// console.log('Secrets loaded:', this.secrets);
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();
}
}