first commit
This commit is contained in:
commit
60f8e249fa
38 files changed
+15851
No files matched your search
+56
@@ -0,0 +1,56 @@
|
|||||||
|
# compiled output
|
||||||
|
/dist
|
||||||
|
/node_modules
|
||||||
|
/build
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Tests
|
||||||
|
/coverage
|
||||||
|
/.nyc_output
|
||||||
|
|
||||||
|
# IDEs and editors
|
||||||
|
/.idea
|
||||||
|
.project
|
||||||
|
.classpath
|
||||||
|
.c9/
|
||||||
|
*.launch
|
||||||
|
.settings/
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# IDE - VSCode
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
!.vscode/launch.json
|
||||||
|
!.vscode/extensions.json
|
||||||
|
|
||||||
|
# dotenv environment variable files
|
||||||
|
.env
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# temp directory
|
||||||
|
.temp
|
||||||
|
.tmp
|
||||||
|
|
||||||
|
# Runtime data
|
||||||
|
pids
|
||||||
|
*.pid
|
||||||
|
*.seed
|
||||||
|
*.pid.lock
|
||||||
|
|
||||||
|
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||||
|
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||||
|
</p>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compile and run the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ npm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ npm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ npm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ npm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ npm run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||||
|
|
||||||
|
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install -g @nestjs/mau
|
||||||
|
$ mau deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
Check out a few resources that may come in handy when working with NestJS:
|
||||||
|
|
||||||
|
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||||
|
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||||
|
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||||
|
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||||
|
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||||
|
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||||
|
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||||
|
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||||
|
|
||||||
|
## Stay in touch
|
||||||
|
|
||||||
|
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||||
|
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||||
|
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
INFISICAL_PROJECT_ID=1ebbd0b9-7f76-40fb-91c3-9cf0f12a1510
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
INFISICAL_CLIENT_SECRET=
|
||||||
|
INFISICAL_CLIENT_ID=
|
||||||
|
INFISICAL_PROJECT_ID=1ebbd0b9-7f76-40fb-91c3-9cf0f12a1510
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
INFISICAL_PROJECT_ID=1ebbd0b9-7f76-40fb-91c3-9cf0f12a1510
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
INFISICAL_PROJECT_ID=1ebbd0b9-7f76-40fb-91c3-9cf0f12a1510
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// @ts-check
|
||||||
|
import eslint from '@eslint/js';
|
||||||
|
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||||
|
import globals from 'globals';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{
|
||||||
|
ignores: ['eslint.config.mjs'],
|
||||||
|
},
|
||||||
|
eslint.configs.recommended,
|
||||||
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
|
eslintPluginPrettierRecommended,
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
...globals.jest,
|
||||||
|
},
|
||||||
|
sourceType: 'commonjs',
|
||||||
|
parserOptions: {
|
||||||
|
projectService: true,
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-floating-promises': 'warn',
|
||||||
|
'@typescript-eslint/no-unsafe-argument': 'warn'
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIICITCCAaegAwIBAgIUf2L3kUQyOmHanquEvwwA12ynkskwCgYIKoZIzj0EAwMw
|
||||||
|
TzEUMBIGA1UEBhMLU291dGggS29yZWExEDAOBgNVBAoTB2RhaHllb24xEDAOBgNV
|
||||||
|
BAsTB2RhaHllb24xEzARBgNVBAMTCkRhaHllb24gQ0EwIBcNMjUxMTA2MTY1MjAy
|
||||||
|
WhgPMjA5OTExMDcwMDAwMDBaME8xFDASBgNVBAYTC1NvdXRoIEtvcmVhMRAwDgYD
|
||||||
|
VQQKEwdkYWh5ZW9uMRAwDgYDVQQLEwdkYWh5ZW9uMRMwEQYDVQQDEwpEYWh5ZW9u
|
||||||
|
IENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDg7JTmOwRcXWYgj35NBA2uGw7IW4
|
||||||
|
KbLnDbA9300VBBlkVyDn3CvyRIyFfaXPHq8x2FHjqYLUZ3IDf6dQcyYHUb1870Yn
|
||||||
|
vk3UeMqep9IohHmhr/lF1BHLeENWEqm03IaLo0IwQDAPBgNVHRMBAf8EBTADAQH/
|
||||||
|
MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUrumMDB03WVpnVKw9P73zYfGz2T4w
|
||||||
|
CgYIKoZIzj0EAwMDaAAwZQIwb6GJFNQzTP4RZrH/gTjUI/JVn5jIkSod2yI1Jyxl
|
||||||
|
f1GY5unPdfvttLFZ+DcE/vMrAjEA9YkRItuBmHlwmpvc0OJrCFnizNdDmAuPKhxG
|
||||||
|
TaH+34XUXICB4648beZejWWhZ61D
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# [System.Environment]::SetEnvironmentVariable("NODE_ENV", $null)
|
||||||
|
|
||||||
|
# NODE_ENV 환경 변수가 설정되어 있지 않으면 'dev'로 설정
|
||||||
|
if (-not $env:NODE_ENV) {
|
||||||
|
$env:NODE_ENV = 'dev'
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isMacOS -or $isLinux) {
|
||||||
|
$env:ENV_FILE = "$PSScriptRoot/env-vars/$env:NODE_ENV.env"
|
||||||
|
$env:AWS_CREDENTIALS_FILE = "$env:HOME/.aws/credentials"
|
||||||
|
$env:DAHYEON_GLOBAL_ENVIRONMENT_FILE = "$env:HOME/source/global-env-vars.txt"
|
||||||
|
} elseif ($isWindows) {
|
||||||
|
$env:ENV_FILE = "$PSScriptRoot\env-vars\$env:NODE_ENV.env"
|
||||||
|
$env:AWS_CREDENTIALS_FILE = "$env:USERPROFILE\.aws\credentials"
|
||||||
|
$env:DAHYEON_GLOBAL_ENVIRONMENT_FILE = "$env:USERPROFILE/source/global-env-vars.txt"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 환경 변수 파일 확인
|
||||||
|
if (-Not (Test-Path $env:ENV_FILE)) {
|
||||||
|
Write-Error "The file '$env:ENV_FILE' does not exist."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# 'dahyeon-local.env' 파일에서 환경 변수 설정
|
||||||
|
Get-Content $env:ENV_FILE | ForEach-Object {
|
||||||
|
if ($_ -match '^\s*([^#]+?)\s*=\s*(.*)$') {
|
||||||
|
$key, $value = $matches[1].Trim(), $matches[2].Trim().Trim("`"")
|
||||||
|
[System.Environment]::SetEnvironmentVariable($key, $value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# AWS 자격 증명 파일 확인
|
||||||
|
if (-Not (Test-Path $env:AWS_CREDENTIALS_FILE)) {
|
||||||
|
Write-Error "The AWS credentials file '$env:AWS_CREDENTIALS_FILE' does not exist."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# 공통 환경변수 파일 확인
|
||||||
|
if (-Not (Test-Path $env:DAHYEON_GLOBAL_ENVIRONMENT_FILE)) {
|
||||||
|
Write-Error "The global environment variables file '$env:DAHYEON_GLOBAL_ENVIRONMENT_FILE' does not exist."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# AWS 자격 증명 파일에서 환경 변수 설정
|
||||||
|
Get-Content $env:AWS_CREDENTIALS_FILE | Where-Object { $_ -match '^\s*([^#=\[]+?)\s*=\s*(.*)$' } | ForEach-Object {
|
||||||
|
$key, $value = $matches[1].Trim(), $matches[2].Trim()
|
||||||
|
$envKey = ($key -replace ' ', '_').ToUpper()
|
||||||
|
[System.Environment]::SetEnvironmentVariable($envKey, $value)
|
||||||
|
}
|
||||||
|
|
||||||
|
# 공통 환경변수 파일에서 환경 변수 설정
|
||||||
|
Get-Content $env:DAHYEON_GLOBAL_ENVIRONMENT_FILE | Where-Object { $_ -match '^\s*([^#=\[]+?)\s*=\s*(.*)$' } | ForEach-Object {
|
||||||
|
$key, $value = $matches[1].Trim(), $matches[2].Trim()
|
||||||
|
$envKey = ($key -replace ' ', '_').ToUpper()
|
||||||
|
[System.Environment]::SetEnvironmentVariable($envKey, $value)
|
||||||
|
}
|
||||||
|
|
||||||
|
Get-ChildItem Env: | Where-Object { $_.Name -like "*AWS*" -or $_.Name -eq "NODE_ENV" }
|
||||||
|
|
||||||
|
nest start --watch
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+14362
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,82 @@
|
|||||||
|
{
|
||||||
|
"name": "crawler",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"author": "park@dahyeon.us",
|
||||||
|
"private": true,
|
||||||
|
"repository": {
|
||||||
|
"url": "https://git.dahyeon.us/dahyeon/crawler.git",
|
||||||
|
"type": "git"
|
||||||
|
},
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./launch-server.ps1\"\"",
|
||||||
|
"start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./launch-server.ps1\"\"",
|
||||||
|
"start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./launch-server.ps1\"\"",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:cov": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@infisical/sdk": "^4.0.6",
|
||||||
|
"@nestjs/common": "^11.0.1",
|
||||||
|
"@nestjs/config": "^4.0.2",
|
||||||
|
"@nestjs/core": "^11.0.1",
|
||||||
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
|
"@nestjs/swagger": "^11.2.3",
|
||||||
|
"minio": "^8.0.6",
|
||||||
|
"mongoose": "^9.0.2",
|
||||||
|
"nats": "^2.29.3",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"temporal-polyfill": "^0.3.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/eslintrc": "^3.2.0",
|
||||||
|
"@eslint/js": "^9.18.0",
|
||||||
|
"@nestjs/cli": "^11.0.0",
|
||||||
|
"@nestjs/schematics": "^11.0.0",
|
||||||
|
"@nestjs/testing": "^11.0.1",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
|
"@types/node": "^24.10.4",
|
||||||
|
"@types/supertest": "^6.0.2",
|
||||||
|
"eslint": "^9.18.0",
|
||||||
|
"eslint-config-prettier": "^10.0.1",
|
||||||
|
"eslint-plugin-prettier": "^5.2.2",
|
||||||
|
"globals": "^16.0.0",
|
||||||
|
"jest": "^30.0.0",
|
||||||
|
"prettier": "^3.4.2",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.2.5",
|
||||||
|
"ts-loader": "^9.5.2",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.7.3",
|
||||||
|
"typescript-eslint": "^8.20.0"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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!');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AppController } from './app.controller';
|
||||||
|
import { AppService } from './app.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
envFilePath:
|
||||||
|
process.env.NODE_ENV === 'prod'
|
||||||
|
? '.env.prod'
|
||||||
|
: process.env.NODE_ENV === 'test'
|
||||||
|
? '.env.test'
|
||||||
|
: '.env.dev',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [AppController],
|
||||||
|
providers: [AppService],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AppService {
|
||||||
|
getHello(): string {
|
||||||
|
return 'Hello World!';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
// auth/public.decorator.ts
|
||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED = 'IS_PUBLIC_ACCESS_ALLOWED';
|
||||||
|
export const AllowPublicAccess = () => SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
import { JwtService } from "./jwt.service";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [JwtService],
|
||||||
|
exports: [JwtService],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||||
|
import { EntraIDPayloadClaims, JwtService } from './jwt.service';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import {
|
||||||
|
decodeJwt
|
||||||
|
} from 'jose';
|
||||||
|
|
||||||
|
//request에서 user 정보만
|
||||||
|
export const ExtractUserPayloadFromToken = createParamDecorator(async (data: unknown, ctx: ExecutionContext) => {
|
||||||
|
const request: Request = ctx.switchToHttp().getRequest();
|
||||||
|
const token = request.header('authorization')?.replace('Bearer ', '');
|
||||||
|
const claims = decodeJwt(token!) as EntraIDPayloadClaims
|
||||||
|
// 요청 메타데이터 저장
|
||||||
|
const { aud, iss, iat, nbf, rh, ver, ...accountMetadata } = claims
|
||||||
|
// global.__drizzleContexts = accountMetadata;
|
||||||
|
return accountMetadata;
|
||||||
|
});
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// src/auth/jwt.guard.ts
|
||||||
|
import {
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
ForbiddenException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import { IdentityProviderName, JwtService } from './jwt.service';
|
||||||
|
import { decodeJwt } from 'jose';
|
||||||
|
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtAuthGuard implements CanActivate {
|
||||||
|
constructor(
|
||||||
|
private readonly reflector: Reflector,
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const isPublicAccessAllowed = this.reflector.getAllAndOverride<boolean>(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, [
|
||||||
|
context.getHandler(),
|
||||||
|
context.getClass(),
|
||||||
|
]);
|
||||||
|
if (isPublicAccessAllowed) return true;
|
||||||
|
|
||||||
|
const request = context.switchToHttp().getRequest();
|
||||||
|
const authz = request.headers?.authorization as string | undefined;
|
||||||
|
|
||||||
|
if (!authz || !authz.startsWith('Bearer ')) {
|
||||||
|
throw new UnauthorizedException('Missing or invalid Authorization header');
|
||||||
|
}
|
||||||
|
const token = authz.slice('Bearer '.length).trim();
|
||||||
|
if (!token) {
|
||||||
|
throw new UnauthorizedException('Empty bearer token');
|
||||||
|
}
|
||||||
|
|
||||||
|
// let identityProvider =
|
||||||
|
// this.reflector.getAllAndOverride<IdentityProviderName>(IDP_KEY, [
|
||||||
|
// context.getHandler(),
|
||||||
|
// context.getClass(),
|
||||||
|
// ]);
|
||||||
|
|
||||||
|
// if (!identityProvider) {
|
||||||
|
|
||||||
|
// }
|
||||||
|
let identityProvider: IdentityProviderName;
|
||||||
|
try {
|
||||||
|
const { iss } = decodeJwt(token) as { iss?: string };
|
||||||
|
if (!iss) {
|
||||||
|
throw new UnauthorizedException('Token has no issuer (iss) claim');
|
||||||
|
}
|
||||||
|
identityProvider = this.pickIdPFromIssuer(iss);
|
||||||
|
} catch (e) {
|
||||||
|
throw new UnauthorizedException(
|
||||||
|
e instanceof Error ? e.message : 'Unable to decode token',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const verifyResult = await this.jwtService.verify(token, identityProvider);
|
||||||
|
request.user = verifyResult.payload;
|
||||||
|
request.tokenHeader = verifyResult.protectedHeader;
|
||||||
|
request.identityProvider = identityProvider;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : 'JWT verification failed';
|
||||||
|
// iss/aud 불일치는 보통 401, 접근권한 이슈는 403 (여기선 401로 통일)
|
||||||
|
throw new UnauthorizedException(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* issuer(iss)로부터 IdP 추정
|
||||||
|
* - Entra ID: https://login.microsoftonline.com/<tenant>/v2.0
|
||||||
|
* - Cognito: https://cognito-idp.<region>.amazonaws.com/<userPoolId>
|
||||||
|
*/
|
||||||
|
private pickIdPFromIssuer(issuer: string): IdentityProviderName {
|
||||||
|
const lower = issuer.toLowerCase();
|
||||||
|
|
||||||
|
if (lower.includes('login.microsoftonline.com')) {
|
||||||
|
return 'MICROSOFT_ENTRAID';
|
||||||
|
}
|
||||||
|
if (lower.includes('cognito-idp.') && lower.includes('.amazonaws.com')) {
|
||||||
|
return 'AMAZON_COGNITO';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 필요하다면 여기서 jwtService 내부에 등록된 issuer들로 엄격 매칭하도록 변경 가능:
|
||||||
|
// const configuredIssuers = this.jwtService.getConfiguredIssuers?.();
|
||||||
|
// ...
|
||||||
|
|
||||||
|
throw new ForbiddenException(`Unknown issuer: ${issuer}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
// src/auth/azure-jwt.service.ts
|
||||||
|
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { SecretService } from '../secret/secret.service';
|
||||||
|
import {
|
||||||
|
createRemoteJWKSet,
|
||||||
|
jwtVerify,
|
||||||
|
JWTPayload,
|
||||||
|
JWTVerifyResult,
|
||||||
|
} from 'jose';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Microsoft Entra ID 를 IdP로 사용하는 OpenID Connect 인증 관련 모듈.
|
||||||
|
* OIDC 인증 흐름 -> https://learn.microsoft.com/ko-kr/entra/architecture/auth-oidc 문서 참조.
|
||||||
|
* 추후 IdP 확장 고려해 IdP 별로 해당 IdP 이름을 접두사에 붙인다.
|
||||||
|
*/
|
||||||
|
export type IdentityProviderName = 'MICROSOFT_ENTRAID' | 'AMAZON_COGNITO';
|
||||||
|
|
||||||
|
// export type IdentityProvider = {
|
||||||
|
// [x in IdentityProviderName]: EntraIDIdentityProviderMetadata
|
||||||
|
// };
|
||||||
|
|
||||||
|
// export type EntraIDIdentityProviderMetadata = {
|
||||||
|
// issuer: string;
|
||||||
|
// authorizationEndpoint: string;
|
||||||
|
// tokenEndpoint: string;
|
||||||
|
// userInfoEndpoint: string;
|
||||||
|
// jwksUri: string;
|
||||||
|
// }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* https://learn.microsoft.com/en-us/entra/identity-platform/access-token-claims-reference
|
||||||
|
* Microsoft Entra access-token의 페이로드 클레임. (v2.0)
|
||||||
|
* {
|
||||||
|
aud: 'd182d8e3-fa47-4b93-a736-8c4b7c25bc97',
|
||||||
|
iss: 'https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863/v2.0',
|
||||||
|
iat: 1762581073,
|
||||||
|
nbf: 1762581073,
|
||||||
|
exp: 1762584973,
|
||||||
|
idp: 'https://sts.windows.net/9188040d-6c67-4c5b-b112-36a304b66dad/',
|
||||||
|
name: '박 다현',
|
||||||
|
nonce: '019a6209-2ad0-7ff3-b602-717dc84110c7',
|
||||||
|
oid: 'f0e47b9f-00cd-4dcc-b324-982c87925be3',
|
||||||
|
preferred_username: 'park@dahyeon.us',
|
||||||
|
prov_data: [ [Object] ],
|
||||||
|
rh: '1.ASsABID4XlPpBEuT22S79JxoY-PYgtFH-pNLpzaMS3wlvJfCAPErAA.',
|
||||||
|
sid: '00a91929-edb8-af0a-4867-1a286d232132',
|
||||||
|
sub: 'wOWxMykMnhSt4ze00IBprHGCXR17VGmpB384UmoJb4I',
|
||||||
|
tid: '5ef88004-e953-4b04-93db-64bbf49c6863',
|
||||||
|
uti: 'Zum6q_BVMkmKGtgKL21UAA',
|
||||||
|
ver: '2.0'
|
||||||
|
},
|
||||||
|
*/
|
||||||
|
export type EntraIDPayloadClaims = {
|
||||||
|
aud: string;
|
||||||
|
iss: string;
|
||||||
|
iat: number;
|
||||||
|
lap: string;
|
||||||
|
nbf: number;
|
||||||
|
exp: number;
|
||||||
|
name: string;
|
||||||
|
nonce: string;
|
||||||
|
oid: string;
|
||||||
|
preferred_username: string;
|
||||||
|
prov_data: [{}],
|
||||||
|
rh: string;
|
||||||
|
sid: string;
|
||||||
|
sub: string;
|
||||||
|
tid: string;
|
||||||
|
uti: string;
|
||||||
|
ver: '2.0';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtService implements OnModuleInit {
|
||||||
|
private jwtClaimAudience: string;
|
||||||
|
|
||||||
|
private MICROSOFT_ENTRAID_tenantId: string;
|
||||||
|
private MICROSOFT_ENTRAID_allowedAlgs: string;
|
||||||
|
private MICROSOFT_ENTRAID_issuer: string;
|
||||||
|
private MICROSOFT_ENTRAID_jwksUri: string;
|
||||||
|
private MICROSOFT_ENTRAID_jwks: () => Promise<CryptoKey>;
|
||||||
|
|
||||||
|
private readonly tokenSigningAlgValuesSupported = ['RS256'];
|
||||||
|
private readonly clockTolerance =
|
||||||
|
Number(process.env.JWT_CLOCK_TOLERANCE || 5); // seconds
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly secretService: SecretService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async onModuleInit() {
|
||||||
|
await this.secretService.ready()
|
||||||
|
this.jwtClaimAudience = await this.secretService.get('JWT_CLAIM_AUDIENCE')
|
||||||
|
|
||||||
|
this.MICROSOFT_ENTRAID_tenantId = await this.secretService.get('MICROSOFT_ENTRAID_TENANT_ID')
|
||||||
|
this.MICROSOFT_ENTRAID_allowedAlgs = await this.secretService.get('MICROSOFT_ENTRAID_ALLOWED_ALGS')
|
||||||
|
this.MICROSOFT_ENTRAID_issuer = `https://login.microsoftonline.com/${this.MICROSOFT_ENTRAID_tenantId}/v2.0`;
|
||||||
|
this.MICROSOFT_ENTRAID_jwksUri = `https://login.microsoftonline.com/common/discovery/v2.0/keys`;
|
||||||
|
const remoteJWKSet = createRemoteJWKSet(new URL(this.MICROSOFT_ENTRAID_jwksUri), {
|
||||||
|
// cache: true,
|
||||||
|
cooldownDuration: 30_000,
|
||||||
|
timeoutDuration: 10_000,
|
||||||
|
})
|
||||||
|
this.MICROSOFT_ENTRAID_jwks = remoteJWKSet;
|
||||||
|
try {
|
||||||
|
await remoteJWKSet.reload();
|
||||||
|
} catch (e) {
|
||||||
|
// 초기 로드 실패는 무시하거나 로깅
|
||||||
|
console.warn('Failed to preload Entra JWKs:', e);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(remoteJWKSet.jwks(), 'Entra JWKs loaded');
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authorization: Bearer <token> 의 <token> 부분을 검증.
|
||||||
|
* - iss: IdP 별 설정에 따라.
|
||||||
|
* - aud: Application ID URI와 정확히 일치해야 함
|
||||||
|
* - alg: IdP 마다 허용된 설정에 따라야 함
|
||||||
|
*/
|
||||||
|
async verify(
|
||||||
|
token: string,
|
||||||
|
identityProvider: IdentityProviderName
|
||||||
|
): Promise<JWTVerifyResult<JWTPayload>> {
|
||||||
|
console.log('Verifying JWT token');
|
||||||
|
if (!token) {
|
||||||
|
throw new Error('Empty token');
|
||||||
|
}
|
||||||
|
|
||||||
|
// IdP별 설정 매핑
|
||||||
|
const providers: {
|
||||||
|
[x in IdentityProviderName]: {
|
||||||
|
jwks: () => Promise<CryptoKey>;
|
||||||
|
issuer: string;
|
||||||
|
audience: string;
|
||||||
|
extraValidate?: (payload: JWTPayload) => void;
|
||||||
|
};
|
||||||
|
} = {
|
||||||
|
MICROSOFT_ENTRAID: {
|
||||||
|
jwks: this.MICROSOFT_ENTRAID_jwks,
|
||||||
|
issuer: this.MICROSOFT_ENTRAID_issuer,
|
||||||
|
audience: this.jwtClaimAudience,
|
||||||
|
extraValidate: (payload: JWTPayload) => {
|
||||||
|
// AAD v2 토큰 전용 추가 검증
|
||||||
|
if (payload['ver'] && payload['ver'] !== '2.0') {
|
||||||
|
throw new Error(`Unsupported AAD token version: ${payload['ver']}`);
|
||||||
|
}
|
||||||
|
if (payload['tid'] && payload['tid'] !== this.MICROSOFT_ENTRAID_tenantId) {
|
||||||
|
throw new Error(`Unexpected tenant: ${payload['tid']}`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
AMAZON_COGNITO: {
|
||||||
|
// TODO : Cognito 통합.. 언젠가...
|
||||||
|
jwks: this['AMAZON_COGNITO_jwks'],
|
||||||
|
issuer: this['AMAZON_COGNITO_issuer'],
|
||||||
|
audience: this['AMAZON_COGNITO_audience'],
|
||||||
|
extraValidate: (payload: JWTPayload) => {
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const provider = providers[identityProvider];
|
||||||
|
console.log('Using identity provider:', provider.jwks);
|
||||||
|
if (!provider?.jwks || !provider?.issuer || !provider?.audience) {
|
||||||
|
throw new Error(`Identity provider not configured: ${identityProvider}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowedAlgs =
|
||||||
|
(this.MICROSOFT_ENTRAID_allowedAlgs
|
||||||
|
? this.MICROSOFT_ENTRAID_allowedAlgs.split(',').map(s => s.trim()).filter(Boolean)
|
||||||
|
: this.tokenSigningAlgValuesSupported) as string[];
|
||||||
|
|
||||||
|
let result
|
||||||
|
|
||||||
|
try {
|
||||||
|
result = await jwtVerify(token, provider.jwks, {
|
||||||
|
issuer: provider.issuer,
|
||||||
|
audience: provider.audience,
|
||||||
|
algorithms: allowedAlgs,
|
||||||
|
clockTolerance: this.clockTolerance,
|
||||||
|
});
|
||||||
|
console.log(result, 'jwt verify result');
|
||||||
|
} catch (e) {
|
||||||
|
// const msg = e instanceof Error ? e.message : 'JWT verification error';
|
||||||
|
// throw new Error(`JWT verification failed: ${msg}`);
|
||||||
|
console.log('JWT verification failed:', e);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { payload, protectedHeader } = result;
|
||||||
|
|
||||||
|
if (!allowedAlgs.includes(protectedHeader.alg as string)) {
|
||||||
|
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
provider.extraValidate?.(payload);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,243 @@
|
|||||||
|
import mongoose, { Schema, Document, HydratedDocument } from 'mongoose';
|
||||||
|
import { ModelDefinition } from './types';
|
||||||
|
|
||||||
|
export interface MongooseTimestamps {
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Metadata {
|
||||||
|
key: string;
|
||||||
|
value: string | any[]
|
||||||
|
dataType: 'string' | 'number' | 'boolean' | 'array' | 'json';
|
||||||
|
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>
|
||||||
|
|
||||||
|
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[]) {
|
||||||
|
// 특정 키인 경우 value가 null 또는 빈 문자열이 아니어야 함
|
||||||
|
// if (this.key === 'requiredKey') {
|
||||||
|
// return typeof v === 'string' && v.trim().length > 0;
|
||||||
|
// }
|
||||||
|
// 그렇지 않은 경우 value는 null 또는 문자열, Array이어야 함
|
||||||
|
return 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 or array for key "${this.key}".`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
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: [],
|
||||||
|
validator: function (v: string | any[] | number | boolean | object | null) {
|
||||||
|
// 'this'는 현재 검증 중인 Metadata 서브 도큐먼트를 가리킵니다.
|
||||||
|
const dataType = (this as Metadata).dataType;
|
||||||
|
|
||||||
|
if (v === null) {
|
||||||
|
return true; // null은 항상 허용 (required: false이므로)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (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':
|
||||||
|
// JSON은 객체 형태일 수 있습니다.
|
||||||
|
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||||
|
default:
|
||||||
|
// 'string'이 기본값이므로 이쪽으로 빠지는 경우는 드물지만, 방어 코드
|
||||||
|
return typeof v === 'string';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
message: function (props: any) {
|
||||||
|
const dataType = (this as Metadata).dataType;
|
||||||
|
return `Value "${props.value}" does not match the expected data type "${dataType}".`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
}
|
||||||
Vendored
+5
@@ -0,0 +1,5 @@
|
|||||||
|
export interface ModelDefinition {
|
||||||
|
name: string;
|
||||||
|
schema: mongoose.Schema<any>;
|
||||||
|
schemaName?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
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 { JwtService } from './auth/jwt.service';
|
||||||
|
import { MinioModule } from './minio/minio.module';
|
||||||
|
import { AuthModule } from './auth/auth.module';
|
||||||
|
import { DatabaseModule } from './database/database.module';
|
||||||
|
// import { DatabaseModule } from './database/database.module';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
SecretModule,
|
||||||
|
NatsModule,
|
||||||
|
MinioModule,
|
||||||
|
AuthModule,
|
||||||
|
MinioModule,
|
||||||
|
DatabaseModule,
|
||||||
|
],
|
||||||
|
providers: [JwtService],
|
||||||
|
exports: [
|
||||||
|
SecretModule,
|
||||||
|
NatsModule,
|
||||||
|
MinioModule,
|
||||||
|
AuthModule,
|
||||||
|
MinioModule,
|
||||||
|
DatabaseModule,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class GlobalModule {}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
import { MinioService } from "./minio.service";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [MinioService],
|
||||||
|
exports: [MinioService],
|
||||||
|
})
|
||||||
|
export class MinioModule {}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { Injectable, OnModuleInit } from "@nestjs/common";
|
||||||
|
import { SecretService } from "../secret/secret.service";
|
||||||
|
import * as Minio from 'minio'
|
||||||
|
import { Temporal } from "temporal-polyfill";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MinioService implements OnModuleInit {
|
||||||
|
private minioClient: Minio.Client;
|
||||||
|
private endpoint: string;
|
||||||
|
private accessKey: string;
|
||||||
|
private secretKey: string;
|
||||||
|
|
||||||
|
private readonly bucketName = 'wiki-image'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly secretService: SecretService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async onModuleInit() {
|
||||||
|
await this.secretService.ready()
|
||||||
|
|
||||||
|
this.endpoint = await this.secretService.get('MINIO_ENDPOINT')
|
||||||
|
this.accessKey = await this.secretService.get('MINIO_ACCESS_KEY')
|
||||||
|
this.secretKey = await this.secretService.get('MINIO_SECRET_KEY')
|
||||||
|
|
||||||
|
this.minioClient = new Minio.Client({
|
||||||
|
endPoint: this.endpoint,
|
||||||
|
useSSL: true,
|
||||||
|
accessKey: this.accessKey,
|
||||||
|
secretKey: this.secretKey,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// uploadFile(file: Buffer): Promise<string>
|
||||||
|
// uploadFile(file: Express.Multer.File): Promise<string>
|
||||||
|
public async uploadFile(file: Express.Multer.File): Promise<string> {
|
||||||
|
const date = Temporal.Now.plainDateISO().toString()
|
||||||
|
const s3ObjectKey = `${date}/${file.originalname}`
|
||||||
|
const metaData = {
|
||||||
|
'Content-Type': file.mimetype,
|
||||||
|
'X-Amz-Meta-serviceName': 'wiki',
|
||||||
|
}
|
||||||
|
const fileBuffer = Buffer.from(file.buffer)
|
||||||
|
await this.minioClient.putObject(this.bucketName, s3ObjectKey, fileBuffer, file.size, metaData)
|
||||||
|
return s3ObjectKey
|
||||||
|
}
|
||||||
|
|
||||||
|
public async uploadImage(file: Express.Multer.File): Promise<string> {
|
||||||
|
const date = Temporal.Now.plainDateISO().toString()
|
||||||
|
const s3ObjectKey = `${date}/${file.originalname.split('.')[0]}/original.${file.originalname.split('.').pop()}`
|
||||||
|
console.log(s3ObjectKey)
|
||||||
|
const metaData = {
|
||||||
|
'Content-Type': file.mimetype,
|
||||||
|
'X-Amz-Meta-serviceName': 'wiki',
|
||||||
|
}
|
||||||
|
const fileBuffer = Buffer.from(file.buffer)
|
||||||
|
await this.minioClient.putObject(this.bucketName, s3ObjectKey, fileBuffer, file.size, metaData)
|
||||||
|
return s3ObjectKey
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
import { NatsService } from "./nats.service";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [NatsService],
|
||||||
|
exports: [NatsService],
|
||||||
|
})
|
||||||
|
export class NatsModule {}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
|
||||||
|
import { NatsConnection, StringCodec, 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;
|
||||||
|
|
||||||
|
private readonly stringCodec = StringCodec();
|
||||||
|
|
||||||
|
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({
|
||||||
|
name : "wiki-server",
|
||||||
|
servers: [this.endpoint],
|
||||||
|
tls: {
|
||||||
|
ca: cacert,
|
||||||
|
|
||||||
|
},
|
||||||
|
maxReconnectAttempts: -1,
|
||||||
|
reconnectTimeWait: 500,
|
||||||
|
reconnect: true,
|
||||||
|
pingInterval: 20000,
|
||||||
|
timeout: 5000,
|
||||||
|
user: this.user,
|
||||||
|
pass: this.password
|
||||||
|
});
|
||||||
|
// const result = await this.natsClient.status();
|
||||||
|
// console.log(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
async onModuleDestroy() {
|
||||||
|
if (!this.natsClient) return;
|
||||||
|
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,10 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,25 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import { App } from 'supertest/types';
|
||||||
|
import { AppModule } from './../src/app.module';
|
||||||
|
|
||||||
|
describe('AppController (e2e)', () => {
|
||||||
|
let app: INestApplication<App>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleFixture.createNestApplication();
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/ (GET)', () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get('/')
|
||||||
|
.expect(200)
|
||||||
|
.expect('Hello World!');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": ["js", "json", "ts"],
|
||||||
|
"rootDir": ".",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "nodenext",
|
||||||
|
"moduleResolution": "nodenext",
|
||||||
|
"resolvePackageJsonExports": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"declaration": true,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "ES2023",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictNullChecks": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"strictBindCallApply": false,
|
||||||
|
"noFallthroughCasesInSwitch": false
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user