Adds Drizzle ORM with Infisical for secure database management

Integrates Drizzle ORM to provide a type-safe and modern solution for PostgreSQL database interactions. Establishes Infisical as the central secret management system, ensuring sensitive database credentials and other environment variables are securely loaded dynamically based on the active environment.

Includes a PowerShell script to standardize environment setup for Drizzle CLI operations, fetching secrets from Infisical and local configuration files. New npm scripts `drizzle:push` and `drizzle:pull` are added to streamline database schema migrations.

Sets up an initial database module with a `DatabaseService` and a sample `users` schema to demonstrate Drizzle's functionality and integration with Infisical secrets.
This commit is contained in:
dahyeon committed 2025-11-09 16:05:18 +00:00
1 parent 6aec3e91b8
commit 469e799b01
13 files changed
+1651 -4

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
import { defineConfig } from 'drizzle-kit';
// Environment variables are loaded by launch-drizzle-executable.ps1
const endpoint = process.env.DATABASE_ENDPOINT;
const user = process.env.DATABASE_USER;
const password = process.env.DATABASE_PASSWORD;
const database = process.env.DATABASE_DATABASE_NAME;
if (!endpoint || !user || !password || !database) {
throw new Error('Missing required database environment variables. Make sure to run via npm script.');
}
export default defineConfig({
out: './drizzle',
schema: './src/modules/global/database/schema.ts',
dialect: 'postgresql',
dbCredentials: {
host: endpoint,
port: 5432,
user: user,
password: password,
database: database,
ssl: false,
},
});
+91
View File
@@ -0,0 +1,91 @@
# [System.Environment]::SetEnvironmentVariable("NODE_ENV", $null)
param(
[Parameter(ValueFromRemainingArguments = $true)]
[string[]] $Rest
)
# 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)
}
# Load secrets from Infisical using Node.js script
Write-Host "Loading secrets from Infisical..."
$secretsOutput = & node "$PSScriptRoot/load-secrets.mjs"
if ($LASTEXITCODE -ne 0) {
Write-Error "Failed to load secrets from Infisical"
exit 1
}
# Parse and set environment variables from Infisical
$secretsOutput | ForEach-Object {
if ($_ -match '^\s*([^=]+?)\s*=\s*(.*)$') {
$key, $value = $matches[1].Trim(), $matches[2].Trim()
[System.Environment]::SetEnvironmentVariable($key, $value)
}
}
Get-ChildItem Env: | Where-Object { $_.Name -like "*DATABASE*" -or $_.Name -like "*AWS*" -or $_.Name -eq "NODE_ENV" }
if ($Rest -and $Rest.Count -gt 0) {
$exe = $Rest[0]
$exeArgs = @()
if ($Rest.Count -gt 1) { $exeArgs = $Rest[1..($Rest.Count - 1)] }
Write-Host "→ Running (array):" $exe $exeArgs
& $exe @exeArgs
} else {
Write-Host "No command provided. Nothing to run."
}
+29
View File
@@ -0,0 +1,29 @@
import { InfisicalSDK } from "@infisical/sdk";
const INFISICAL_SITE_URL = "https://secret-manager.dahyeon.us/"
const INFISICAL_CLIENT_SECRET = process.env.INFISICAL_CLIENT_SECRET;
const INFISICAL_CLIENT_ID = process.env.INFISICAL_CLIENT_ID;
const INFISICAL_PROJECT_ID = process.env.INFISICAL_PROJECT_ID;
if (!INFISICAL_CLIENT_SECRET || !INFISICAL_CLIENT_ID || !INFISICAL_PROJECT_ID) {
console.error("Missing infisical environment variables");
process.exit(1);
}
const infisicalClient = new InfisicalSDK({ siteUrl: INFISICAL_SITE_URL })
await infisicalClient.auth().universalAuth.login({
clientId: INFISICAL_CLIENT_ID,
clientSecret: INFISICAL_CLIENT_SECRET,
});
const res = await infisicalClient.secrets().listSecrets({
environment: process.env.NODE_ENV === 'prod' ? 'prod' : process.env.NODE_ENV === 'test' ? 'staging' : 'dev',
projectId: INFISICAL_PROJECT_ID,
});
// Output as environment variable format for PowerShell to consume
for (const s of res.secrets) {
console.log(`${s.secretKey}=${s.secretValue}`);
}
+76
View File
@@ -0,0 +1,76 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.secrets = void 0;
var sdk_1 = require("@infisical/sdk");
var INFISICAL_SITE_URL = "https://secret-manager.dahyeon.us/";
var INFISICAL_CLIENT_SECRET = process.env.INFISICAL_CLIENT_SECRET;
var INFISICAL_CLIENT_ID = process.env.INFISICAL_CLIENT_ID;
var INFISICAL_PROJECT_ID = process.env.INFISICAL_PROJECT_ID;
var infisicalClient = new sdk_1.InfisicalSDK({ siteUrl: INFISICAL_SITE_URL });
exports.secrets = null;
var fetchSecrets = function () { return __awaiter(void 0, void 0, void 0, function () {
var res, map, _i, _a, s;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!INFISICAL_CLIENT_SECRET || !INFISICAL_CLIENT_ID || !INFISICAL_PROJECT_ID) {
throw new Error("Missing infisical environment variables");
}
return [4 /*yield*/, infisicalClient.auth().universalAuth.login({
clientId: INFISICAL_CLIENT_ID,
clientSecret: INFISICAL_CLIENT_SECRET,
})];
case 1:
_b.sent();
return [4 /*yield*/, infisicalClient.secrets().listSecrets({
environment: process.env.NODE_ENV === 'prod' ? 'prod' : process.env.NODE_ENV === 'test' ? 'staging' : 'dev',
projectId: INFISICAL_PROJECT_ID,
})];
case 2:
res = _b.sent();
map = {};
for (_i = 0, _a = res.secrets; _i < _a.length; _i++) {
s = _a[_i];
map[s.secretKey] = s.secretValue;
}
return [2 /*return*/, map];
}
});
}); };
exports.secrets = await fetchSecrets();
+43
View File
@@ -0,0 +1,43 @@
import { InfisicalSDK } from "@infisical/sdk";
export type SecretMap = Record<string, string | boolean | undefined>;
const INFISICAL_SITE_URL = "https://secret-manager.dahyeon.us/"
const INFISICAL_CLIENT_SECRET = process.env.INFISICAL_CLIENT_SECRET;
const INFISICAL_CLIENT_ID = process.env.INFISICAL_CLIENT_ID;
const INFISICAL_PROJECT_ID = process.env.INFISICAL_PROJECT_ID;
const infisicalClient = new InfisicalSDK({ siteUrl: INFISICAL_SITE_URL })
export let secrets: SecretMap | null = null;
export const fetchSecrets = async (): Promise<SecretMap> => {
if (!INFISICAL_CLIENT_SECRET || !INFISICAL_CLIENT_ID || !INFISICAL_PROJECT_ID) {
throw new Error("Missing infisical environment variables")
}
await infisicalClient.auth().universalAuth.login({
clientId: INFISICAL_CLIENT_ID,
clientSecret: INFISICAL_CLIENT_SECRET,
});
const res = await infisicalClient.secrets().listSecrets({
environment: process.env.NODE_ENV === 'prod' ? 'prod' : process.env.NODE_ENV === 'test' ? 'staging' : 'dev',
projectId: INFISICAL_PROJECT_ID,
});
const map: SecretMap = {};
for (const s of res.secrets) {
map[s.secretKey] = s.secretValue;
}
return map
}
export const initSecrets = async () => {
if (!secrets) {
secrets = await fetchSecrets();
}
return secrets;
}
+1280 -2
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -12,6 +12,8 @@
"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\"\"",
"drizzle:push": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./drizzle/launch-drizzle-executable.ps1\" -- npx drizzle-kit --config ./drizzle/drizzle.config.ts push\"",
"drizzle:pull": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./drizzle/launch-drizzle-executable.ps1\" -- npx drizzle-kit --config ./drizzle/drizzle.config.ts pull\"",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
@@ -26,10 +28,12 @@
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.1",
"drizzle-orm": "^0.44.7",
"jose": "^6.1.0",
"minio": "^8.0.6",
"mongoose": "^8.19.3",
"nats": "^2.29.3",
"pg": "^8.16.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"temporal-polyfill": "^0.3.0"
@@ -44,7 +48,9 @@
"@types/jest": "^30.0.0",
"@types/multer": "^2.0.0",
"@types/node": "^22.10.7",
"@types/pg": "^8.15.6",
"@types/supertest": "^6.0.2",
"drizzle-kit": "^0.31.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
@@ -57,6 +63,7 @@
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"tsx": "^4.20.6",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
@@ -1,12 +1,14 @@
import { Controller, Get, UseGuards } from "@nestjs/common";
import { AccountService } from "./account.service";
import { JwtAuthGuard } from "../global/auth/jwt.guard";
import { AllowPublicAccess } from "../global/auth/allow-public-access.decorator";
@Controller('account')
export class AccountController {
constructor(private readonly accountService: AccountService) {}
@Get('signin')
@AllowPublicAccess()
signIn(): string {
return this.accountService.signIn();
}
+2
View File
@@ -3,10 +3,12 @@ import { Injectable } from "@nestjs/common";
@Injectable()
export class AccountService {
signIn(): string {
//TODO: Implement sign in logic
return 'Sign In Successful';
}
getAccountInfo(): string {
//TODO: Implement get account info logic
console.log('Fetching account information');
return 'Account Information';
}
@@ -0,0 +1,8 @@
import { Module } from "@nestjs/common";
import { DatabaseService } from "./database.service";
@Module({
providers: [DatabaseService],
exports: [DatabaseService],
})
export class DatabaseModule {}
@@ -0,0 +1,75 @@
import { Injectable } from "@nestjs/common";
import { SecretService } from "../secret/secret.service";
import { drizzle, NodePgDatabase } from "drizzle-orm/node-postgres";
import * as pg from 'pg'
import { eq } from "drizzle-orm";
import { usersTable } from "./schema";
@Injectable()
export class DatabaseService {
private endpoint: string;
private user: string;
private password: string;
private databaseName: string;
private dbAdapter: NodePgDatabase<Record<string, never>> & { $client: pg.Client }
private connection: pg.Client
constructor(
private readonly secretService: SecretService
) {}
async onModuleInit() {
await this.secretService.ready();
this.endpoint = await this.secretService.get("DATABASE_ENDPOINT");
this.user = await this.secretService.get("DATABASE_USER");
this.password = await this.secretService.get("DATABASE_PASSWORD");
this.databaseName = await this.secretService.get("DATABASE_DATABASE_NAME");
this.connection = new pg.Client({
user: this.user,
password: this.password,
database: this.databaseName,
host: this.endpoint,
port: 5432,
})
await this.connection.connect();
this.dbAdapter = drizzle(this.connection)
await this.test();
}
async test() {
const user: typeof usersTable.$inferInsert = {
name: 'John',
age: 30,
email: 'john@example.com',
};
await this.dbAdapter.insert(usersTable).values(user);
console.log('New user created!')
const users = await this.dbAdapter.select().from(usersTable);
console.log('Getting all users from the database: ', users)
/*
const users: {
id: number;
name: string;
age: number;
email: string;
}[]
*/
await this.dbAdapter
.update(usersTable)
.set({
age: 31,
})
.where(eq(usersTable.email, user.email));
console.log('User info updated!')
await this.dbAdapter.delete(usersTable).where(eq(usersTable.email, user.email));
console.log('User deleted!')
}
}
+10
View File
@@ -0,0 +1,10 @@
import { pgTable } from "drizzle-orm/pg-core";
import { integer } from "drizzle-orm/pg-core";
import { varchar } from "drizzle-orm/pg-core";
export const usersTable = pgTable("users", {
id: integer().primaryKey().generatedAlwaysAsIdentity(),
name: varchar({ length: 255 }).notNull(),
age: integer().notNull(),
email: varchar({ length: 255 }).notNull().unique(),
});
+3 -2
View File
@@ -5,11 +5,12 @@ 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';
@Global()
@Module({
imports: [SecretModule, NatsModule, MinioModule, AuthModule, MinioModule],
imports: [SecretModule, NatsModule, MinioModule, AuthModule, MinioModule, DatabaseModule],
providers: [JwtService],
exports: [SecretModule, NatsModule, MinioModule, AuthModule, MinioModule],
exports: [SecretModule, NatsModule, MinioModule, AuthModule, MinioModule, DatabaseModule],
})
export class GlobalModule {}