Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,24 @@ SWAGGER_PASS=admin
RATE_LIMIT_MAX=200
RATE_LIMIT_WINDOW=1 minute # 'ms', 's', 'm', 'h', 'd', 'second', 'seconds', 'minute', 'minutes', 'hour', 'hours', 'day', 'days', 'week'
RATE_LIMIT_SKIP_PATHS=/docs # '/docs', '/health', '/status'

# Database Config
DATABASE_URL=postgres://postgres:admin123@localhost:5432/omninexus

# DATABASE
DB_USER=postgres
DB_PASSWORD=admin123
DB_NAME=omninexus
DB_PORT=5432

# TUNING POSTGRES (baseline decente)
DB_MAX_CONNECTIONS=100
DB_SHARED_BUFFERS=128MB
DB_WORK_MEM=4MB
DB_MAINTENANCE_WORK_MEM=64MB

# RESOURCE LIMITS - DATABASE
DB_CPU_LIMIT=0.50
DB_MEMORY_LIMIT=512M
DB_CPU_RESERVATION=0.25
DB_MEMORY_RESERVATION=256M
8 changes: 8 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,21 @@
"bunx",
"codar",
"commitlint",
"cpus",
"dpage",
"dtos",
"Fastify",
"GITHUB",
"healthcheck",
"isready",
"omni",
"omninexus",
"oxlint",
"Oxlint",
"pgadmin",
"PGADMIN",
"postgres",
"postgresql",
"rcosystem",
"Stivan",
"treeify"
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,29 @@ Acesse a documentação em: `http://localhost:3000/docs`

---

## 🗄️ Gestão de Banco de Dados (Drizzle ORM)

O OmniNexus utiliza o **Drizzle ORM** para garantir máxima performance e *Type Safety*. O gerenciamento do banco de dados (PostgreSQL) é feito através do Bun, utilizando os seguintes comandos:

### Fluxo de Trabalho

Sempre que você alterar o arquivo `src/database/schema.ts`, utilize os comandos abaixo de acordo com a sua necessidade:

| Comando | Descrição | Quando usar? |
| :--- | :--- | :--- |
| `bun run db:push` | Sincroniza o schema diretamente com o banco. | Durante o desenvolvimento rápido (Prototipagem). |
| `bun run db:generate` | Gera arquivos SQL de migração na pasta `/drizzle`. | Antes de realizar um **Commit** para versionar o banco. |
| `bun run db:migrate` | Aplica as migrações SQL pendentes no banco. | Em ambientes de **Produção** ou CI/CD. |
| `bun run db:studio` | Abre uma interface técnica para visualizar os dados. | Sempre que precisar validar registros manualmente. |

### Exemplo Prático:
1. Altere uma coluna em `src/database/schema.ts`.
2. Execute `bun run db:push` para testar imediatamente no Docker.
3. Após validar, execute `bun run db:generate` para criar o histórico de migração.
4. Faça o commit dos arquivos gerados na pasta `/drizzle`.

---

## 🤝 Contribuição e Commits

Adoramos contribuições! Para manter a rastreabilidade e o histórico limpo, utilizamos **Conventional Commits**.
Expand Down
191 changes: 191 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

68 changes: 68 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
version: "3.9"

name: omninexus

services:
db:
image: postgres:17-alpine
container_name: omninexus-db

restart: unless-stopped

env_file:
- .env

environment:
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: ${DB_NAME}

command: >
postgres
-c max_connections=${DB_MAX_CONNECTIONS}
-c shared_buffers=${DB_SHARED_BUFFERS}
-c work_mem=${DB_WORK_MEM}
-c maintenance_work_mem=${DB_MAINTENANCE_WORK_MEM}

ports:
- "${DB_PORT}:5432"

volumes:
- postgres_data:/var/lib/postgresql/data

networks:
- backend

healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s

mem_limit: ${DB_MEMORY_LIMIT}
cpus: ${DB_CPU_LIMIT}

deploy:
resources:
limits:
cpus: "${DB_CPU_LIMIT}"
memory: "${DB_MEMORY_LIMIT}"
reservations:
cpus: "${DB_CPU_RESERVATION}"
memory: "${DB_MEMORY_RESERVATION}"

logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"

networks:
backend:
name: omninexus-network
driver: bridge

volumes:
postgres_data:
name: omninexus-postgres-data
10 changes: 10 additions & 0 deletions drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineConfig } from 'drizzle-kit'

export default defineConfig({
schema: './src/database/schema.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL ?? '',
},
})
10 changes: 10 additions & 0 deletions drizzle/0000_aromatic_xavin.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE "users" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"name" varchar(255) NOT NULL,
"email" varchar(255) NOT NULL,
"password_hash" text NOT NULL,
"role" varchar(50) DEFAULT 'admin' NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "users_email_unique" UNIQUE("email")
);
84 changes: 84 additions & 0 deletions drizzle/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
{
"id": "aae9bccf-4c78-4deb-9eda-bbaaa7f9635b",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.users": {
"name": "users",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"name": {
"name": "name",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"password_hash": {
"name": "password_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"role": {
"name": "role",
"type": "varchar(50)",
"primaryKey": false,
"notNull": true,
"default": "'admin'"
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"users_email_unique": {
"name": "users_email_unique",
"nullsNotDistinct": false,
"columns": ["email"]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
13 changes: 13 additions & 0 deletions drizzle/meta/_journal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1774700715376,
"tag": "0000_aromatic_xavin",
"breakpoints": true
}
]
}
11 changes: 10 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@
"prepare": "husky",
"release": "semantic-release",
"test": "bun test",
"test:watch": "bun test --watch"
"test:watch": "bun test --watch",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:push": "drizzle-kit push",
"db:studio": "drizzle-kit studio"
},
"devDependencies": {
"@biomejs/biome": "2.4.7",
Expand All @@ -58,7 +62,9 @@
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/exec": "^7.1.0",
"@semantic-release/git": "^10.0.1",
"@types/bcrypt": "^6.0.0",
"@types/bun": "latest",
"drizzle-kit": "^0.31.10",
"husky": "^9.1.7",
"lint-staged": "^16.4.0",
"oxlint": "^1.57.0",
Expand All @@ -71,10 +77,13 @@
"@fastify/rate-limit": "^10.3.0",
"@fastify/swagger": "^9.7.0",
"@scalar/fastify-api-reference": "^1.49.5",
"bcrypt": "^6.0.0",
"drizzle-orm": "^0.45.2",
"fastify": "^5.8.4",
"fastify-type-provider-zod": "^6.1.0",
"i18next": "^25.10.10",
"pino-roll": "^4.0.0",
"postgres": "^3.4.8",
"zod": "^4.3.6"
},
"peerDependencies": {
Expand Down
7 changes: 7 additions & 0 deletions src/database/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import { env } from '../env/env'
import * as schema from './schema'

const client = postgres(env.DATABASE_URL)
export const db = drizzle(client, { schema })
15 changes: 15 additions & 0 deletions src/database/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { pgTable, text, timestamp, uuid, varchar } from 'drizzle-orm/pg-core'

export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
name: varchar('name', { length: 255 }).notNull(),
email: varchar('email', { length: 255 }).notNull().unique(),
passwordHash: text('password_hash').notNull(),
role: varchar('role', { length: 50 }).notNull().default('admin'),
createdAt: timestamp('created_at', { withTimezone: true })
.defaultNow()
.notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true })
.defaultNow()
.notNull(),
})
3 changes: 3 additions & 0 deletions src/env/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const envSchema = z.object({
.map((v) => v.trim())
.filter(Boolean),
),

// Database Config
DATABASE_URL: z.string(),
})

const _env = envSchema.safeParse(Bun.env)
Expand Down
29 changes: 29 additions & 0 deletions src/modules/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import bcrypt from 'bcrypt'
import { eq } from 'drizzle-orm'
import { db } from '../../database/db'
import { users } from '../../database/schema'

export const UserService = {
async createMaster(data: { name: string; email: string; password: string }) {
const passwordHash = await bcrypt.hash(data.password, 10)

return await db
.insert(users)
.values({
name: data.name,
email: data.email,
passwordHash,
role: 'admin',
})
.returning({ id: users.id, email: users.email })
},

async findByEmail(email: string) {
const result = await db
.select()
.from(users)
.where(eq(users.email, email))
.limit(1)
return result[0]
},
}
Loading