first commit
This commit is contained in:
commit
9d65fbd235
57 files changed
+15094
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.js';
|
||||
import { moeumModelDefinitions, MoeumModelTypes } from './schema.js';
|
||||
|
||||
@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(
|
||||
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.js';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
providers: [ConnectionService],
|
||||
exports: [ConnectionService],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,182 @@
|
||||
import mongoose, { Schema, Document } from 'mongoose';
|
||||
import { ModelDefinition } from './types';
|
||||
|
||||
export interface Metadata {
|
||||
key: string;
|
||||
value: string | any[] | null;
|
||||
dataType: string;
|
||||
isReserved: boolean;
|
||||
}
|
||||
|
||||
export interface TaxonomyChildItem {
|
||||
title: string;
|
||||
order: number;
|
||||
articleId?: mongoose.Types.ObjectId;
|
||||
slug?: string; //article document의 slug 참조 (임베딩)
|
||||
children?: TaxonomyChildItem[];
|
||||
}
|
||||
|
||||
export interface Taxonomy extends Document {
|
||||
label: string;
|
||||
items: TaxonomyChildItem[];
|
||||
metadatas: Metadata[];
|
||||
}
|
||||
|
||||
export interface ContentSection {
|
||||
heading: string;
|
||||
taxonomies: mongoose.Types.ObjectId[];
|
||||
}
|
||||
|
||||
export interface Content extends Document {
|
||||
key: string;
|
||||
label: string;
|
||||
sections: ContentSection[];
|
||||
}
|
||||
|
||||
export interface Article extends Document {
|
||||
title: string;
|
||||
slug: string;
|
||||
content: string;
|
||||
status: 'draft' | 'published' | 'archived';
|
||||
metadatas: Metadata[];
|
||||
}
|
||||
|
||||
export const MetadataSubSchema = new mongoose.Schema<Metadata>({
|
||||
key: { type: String, required: true },
|
||||
value: {
|
||||
type: mongoose.SchemaTypes.Mixed,
|
||||
required: false, // required: true로 하면 value가 null인 경우 에러 발생
|
||||
default: null,
|
||||
validate: {
|
||||
validator: function (v: string | any[] | null) {
|
||||
// 특정 키인 경우 value가 null 또는 빈 문자열이 아니어야 함
|
||||
// if (this.key === 'requiredKey') {
|
||||
// return typeof v === 'string' && v.trim().length > 0;
|
||||
// }
|
||||
// 그렇지 않은 경우 value는 null 또는 문자열, Array이어야 함
|
||||
return v === null || typeof v === 'string' || Array.isArray(v);
|
||||
},
|
||||
message: function (props: any) {
|
||||
if (this.key === 'requiredKey') {
|
||||
return `Value is required for key "${this.key}" and cannot be null or empty.`;
|
||||
}
|
||||
return `Value must be a string, an array, or null for key "${this.key}".`;
|
||||
},
|
||||
},
|
||||
},
|
||||
dataType: { type: String, required: false, default: 'string' },
|
||||
isReserved: { type: Boolean, required: false, default: false },
|
||||
});
|
||||
|
||||
export const TaxonomyChildItemSchema = new Schema(
|
||||
{
|
||||
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 배열로 추가합니다.
|
||||
TaxonomyChildItemSchema.add({
|
||||
children: { type: [TaxonomyChildItemSchema], default: [] },
|
||||
});
|
||||
|
||||
// 2. 메인 도큐먼트 스키마 (Root)
|
||||
export const TaxonomySchema = new Schema(
|
||||
{
|
||||
// items 배열은 위에서 정의한 재귀 스키마를 따름
|
||||
label: { type: String, required: true },
|
||||
items: {
|
||||
type: [TaxonomyChildItemSchema],
|
||||
default: [],
|
||||
},
|
||||
|
||||
// metadata는 구조가 가변적이므로 Mixed 타입 사용
|
||||
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, // createAt, updatedAt 자동 생성
|
||||
collection: 'taxonomy', // 컬렉션 이름 지정
|
||||
},
|
||||
);
|
||||
|
||||
TaxonomySchema.index({ label: 1 }, { unique: true });
|
||||
|
||||
export const ContentSchema = new Schema(
|
||||
{
|
||||
key: { type: String, required: true, unique: true },
|
||||
label: { type: String, required: true },
|
||||
sections: {
|
||||
type: [
|
||||
{
|
||||
heading: { type: String, required: true },
|
||||
taxonomies: [{ type: Schema.Types.ObjectId, ref: 'taxonomy' }],
|
||||
},
|
||||
],
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'content',
|
||||
},
|
||||
);
|
||||
|
||||
export const ArticleSchema = new Schema(
|
||||
{
|
||||
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
@@ -0,0 +1,5 @@
|
||||
export interface ModelDefinition {
|
||||
name: string;
|
||||
schema: mongoose.Schema<any>;
|
||||
schemaName?: string;
|
||||
}
|
||||
Reference in new issue
Block a user