lapeh 2.2.2 → 2.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,89 @@
1
+ # Lapeh Framework Cheatsheet
2
+
3
+ Referensi cepat untuk perintah dan kode yang sering digunakan.
4
+
5
+ ## 💻 CLI Commands
6
+
7
+ | Perintah | Fungsi |
8
+ | :--- | :--- |
9
+ | **`npm run dev`** | Menjalankan server development (hot-reload). |
10
+ | **`npm run typecheck`** | Cek error TypeScript (tanpa compile). |
11
+ | **`npm run lint`** | Cek kode kotor/variabel tidak terpakai. |
12
+ | **`npm run lint:fix`** | Perbaiki kode kotor otomatis. |
13
+ | **`npm run make:module <Name>`** | Buat Controller, Route, & Model sekaligus. |
14
+ | **`npm run make:controller <Name>`** | Buat Controller saja. |
15
+ | **`npm run make:model <Name>`** | Buat Model Prisma saja. |
16
+ | **`npm run prisma:migrate`** | Apply perubahan schema ke DB lokal. |
17
+ | **`npm run db:studio`** | Buka GUI Database. |
18
+ | **`npm run db:seed`** | Isi data dummy. |
19
+ | **`npm run db:reset`** | Hapus DB & mulai dari nol. |
20
+
21
+ ## 🛡️ Validator Rules (Laravel-Style)
22
+
23
+ Gunakan di `Validator.make(data, rules)`.
24
+
25
+ | Rule | Deskripsi | Contoh |
26
+ | :--- | :--- | :--- |
27
+ | `required` | Wajib ada & tidak null. | `"required"` |
28
+ | `string` | Harus text. | `"required|string"` |
29
+ | `number` | Harus angka. | `"required|number"` |
30
+ | `email` | Format email valid. | `"required|email"` |
31
+ | `min:X` | Min panjang/nilai. | `"min:8"` (pass), `"min:18"` (umur) |
32
+ | `max:X` | Max panjang/nilai. | `"max:255"` |
33
+ | `unique:table,col` | Cek unik di DB. | `"unique:users,email"` |
34
+ | `exists:table,col` | Cek exist di DB. | `"exists:roles,id"` |
35
+ | `image` | File harus gambar. | `"required|image"` |
36
+ | `mimes:types` | File extension. | `"mimes:pdf,docx"` |
37
+
38
+ ## 🔑 Authentication
39
+
40
+ **Middleware di Route:**
41
+ ```typescript
42
+ import { requireAuth, requireAdmin } from "@/middleware/auth";
43
+
44
+ router.get("/profile", requireAuth, getProfile); // Login User
45
+ router.delete("/user", requireAuth, requireAdmin, del); // Admin Only
46
+ ```
47
+
48
+ **Akses User di Controller:**
49
+ ```typescript
50
+ // (req as any).user tersedia setelah requireAuth
51
+ const userId = (req as any).user.userId;
52
+ const role = (req as any).user.role;
53
+ ```
54
+
55
+ ## ⚡ Fast Response (Serializer)
56
+
57
+ **1. Schema:**
58
+ ```typescript
59
+ const schema = {
60
+ type: "object",
61
+ properties: {
62
+ id: { type: "string" },
63
+ name: { type: "string" }
64
+ }
65
+ };
66
+ ```
67
+
68
+ **2. Serializer:**
69
+ ```typescript
70
+ const serializer = getSerializer("key-name", createResponseSchema(schema));
71
+ ```
72
+
73
+ **3. Send:**
74
+ ```typescript
75
+ sendFastSuccess(res, 200, serializer, { ...data });
76
+ ```
77
+
78
+ ## 📦 Redis (Cache)
79
+
80
+ ```typescript
81
+ import { redis } from "@/core/redis";
82
+
83
+ // Set Cache (Key, Value, Mode, Detik)
84
+ await redis.set("profile:1", JSON.stringify(data), "EX", 3600);
85
+
86
+ // Get Cache
87
+ const cached = await redis.get("profile:1");
88
+ if (cached) return JSON.parse(cached);
89
+ ```
package/doc/CLI.md ADDED
@@ -0,0 +1,106 @@
1
+ # CLI Tools & Scripts
2
+
3
+ Lapeh Framework dilengkapi dengan berbagai script CLI untuk mempercepat proses development, mulai dari generate code hingga manajemen database.
4
+
5
+ Semua perintah dijalankan menggunakan `npm run <command>`.
6
+
7
+ ## Code Generators
8
+
9
+ Gunakan perintah ini untuk membuat file boilerplate secara otomatis.
10
+
11
+ ### 1. Membuat Module Lengkap (`make:module`)
12
+ Membuat Controller, Route, dan Model (Schema) sekaligus.
13
+
14
+ ```bash
15
+ npm run make:module <nama-module>
16
+ ```
17
+ **Contoh:** `npm run make:module Product`
18
+
19
+ Output:
20
+ - `src/controllers/productController.ts`
21
+ - `src/routes/product.ts`
22
+ - `src/models/product.prisma`
23
+
24
+ ### 2. Membuat Controller (`make:controller`)
25
+ Hanya membuat file controller dengan method CRUD dasar.
26
+
27
+ ```bash
28
+ npm run make:controller <nama-controller>
29
+ ```
30
+ **Contoh:** `npm run make:controller Order` (Akan membuat `src/controllers/orderController.ts`)
31
+
32
+ ### 3. Membuat Model Database (`make:model`)
33
+ Hanya membuat file schema Prisma baru.
34
+
35
+ ```bash
36
+ npm run make:model <nama-model>
37
+ ```
38
+ **Contoh:** `npm run make:model Transaction` (Akan membuat `src/models/transaction.prisma`)
39
+
40
+ ## Database Management (Prisma)
41
+
42
+ Framework ini menggunakan sistem **Multi-File Schema**. Anda tidak mengedit `schema.prisma` secara langsung, melainkan mengedit file kecil di `src/models/*.prisma`.
43
+
44
+ ### 1. Migrasi Database (`prisma:migrate`)
45
+ Jalankan setiap kali Anda mengubah definisi model di `src/models/*.prisma`.
46
+
47
+ ```bash
48
+ npm run prisma:migrate
49
+ ```
50
+ Perintah ini akan:
51
+ 1. Menggabungkan semua file `.prisma` di `src/models/` menjadi satu `prisma/schema.prisma`.
52
+ 2. Membuat file migrasi SQL.
53
+ 3. Menerapkan perubahan ke database lokal.
54
+ 4. Men-generate ulang Prisma Client (Type Definitions).
55
+
56
+ ### 2. Deploy ke Production (`prisma:deploy`)
57
+ Gunakan di server production. Hanya menerapkan migrasi yang sudah ada tanpa reset data.
58
+
59
+ ```bash
60
+ npm run prisma:deploy
61
+ ```
62
+
63
+ ### 3. Database Studio (`db:studio`)
64
+ Membuka GUI di browser untuk melihat dan mengedit data database.
65
+
66
+ ```bash
67
+ npm run db:studio
68
+ ```
69
+
70
+ ### 4. Seeding Data (`db:seed`)
71
+ Mengisi database dengan data awal yang didefinisikan di `prisma/seed.ts`.
72
+
73
+ ```bash
74
+ npm run db:seed
75
+ ```
76
+
77
+ ### 5. Reset Database (`db:reset`)
78
+ **PERINGATAN:** Menghapus semua data dan tabel, lalu menjalankan migrasi dari awal.
79
+
80
+ ```bash
81
+ npm run db:reset
82
+ ```
83
+
84
+ ## Code Quality & Utilities
85
+
86
+ ### 1. Linting (`lint`)
87
+ Memeriksa kode dari error, variabel tidak terpakai, dan gaya penulisan.
88
+
89
+ ```bash
90
+ npm run lint
91
+ ```
92
+ Gunakan `npm run lint:fix` untuk memperbaiki error otomatis.
93
+
94
+ ### 2. Type Check (`typecheck`)
95
+ Memeriksa error tipe data TypeScript tanpa melakukan compile.
96
+
97
+ ```bash
98
+ npm run typecheck
99
+ ```
100
+
101
+ ### 3. Generate JWT Secret (`generate:jwt`)
102
+ Membuat random string aman untuk `JWT_SECRET` di file `.env`.
103
+
104
+ ```bash
105
+ npm run generate:jwt
106
+ ```
@@ -0,0 +1,105 @@
1
+ # Panduan Kontribusi (Contributing Guide)
2
+
3
+ Terima kasih atas ketertarikan Anda untuk berkontribusi pada pengembangan **Lapeh Framework**! 🎉
4
+
5
+ Proyek ini bersifat **Open Source** dan kami sangat menghargai setiap bentuk kontribusi, baik itu perbaikan bug, penambahan fitur, dokumentasi, maupun sekadar laporan error (issue).
6
+
7
+ Dokumen ini akan memandu Anda tentang cara berkontribusi dengan benar dan efisien.
8
+
9
+ ## 🚀 Memulai Kontribusi
10
+
11
+ ### 1. Persiapan Lingkungan (Prerequisites)
12
+ Pastikan Anda sudah menginstal:
13
+ - **Node.js** (v18 ke atas)
14
+ - **Git**
15
+ - **Code Editor** (VS Code disarankan, dengan ekstensi ESLint & Prettier)
16
+
17
+ ### 2. Fork & Clone Repository
18
+ 1. **Fork** repository ini ke akun GitHub Anda (tombol "Fork" di pojok kanan atas).
19
+ 2. **Clone** hasil fork ke komputer lokal Anda:
20
+ ```bash
21
+ git clone https://github.com/USERNAME_ANDA/lapeh.git
22
+ cd lapeh
23
+ ```
24
+ 3. **Tambahkan Remote Upstream** (agar bisa sinkron dengan repo asli):
25
+ ```bash
26
+ git remote add upstream https://github.com/robyajo/lapeh.git
27
+ ```
28
+
29
+ ### 3. Instalasi Dependencies
30
+ ```bash
31
+ npm install
32
+ ```
33
+ Jangan lupa jalankan setup awal untuk database lokal (pastikan PostgreSQL/MySQL jalan):
34
+ ```bash
35
+ cp .env.example .env
36
+ npm run prisma:migrate
37
+ npm run db:seed
38
+ ```
39
+
40
+ ## 🛠️ Workflow Pengembangan
41
+
42
+ ### 1. Buat Branch Baru
43
+ Jangan bekerja langsung di branch `main`. Buat branch baru yang deskriptif:
44
+ ```bash
45
+ git checkout -b feature/tambah-validasi-email
46
+ # atau
47
+ git checkout -b fix/typo-dokumentasi
48
+ ```
49
+
50
+ ### 2. Standar Koding (Coding Standards)
51
+ Kami menerapkan aturan yang ketat demi menjaga kualitas kode.
52
+ - **TypeScript**: Gunakan tipe data eksplisit. Hindari `any` sebisa mungkin.
53
+ - **Linter**: Pastikan tidak ada error ESLint. Variabel tidak terpakai harus dihapus atau diberi prefix `_`.
54
+ - **Formatter**: Kode harus rapi.
55
+
56
+ Sebelum commit, **WAJIB** jalankan perintah ini untuk memastikan kode Anda bersih:
57
+ ```bash
58
+ npm run typecheck # Cek error TypeScript
59
+ npm run lint # Cek error Linter
60
+ ```
61
+
62
+ ### 3. Commit Message Convention
63
+ Gunakan format **Conventional Commits** agar history mudah dibaca:
64
+ - `feat: ...` untuk fitur baru.
65
+ - `fix: ...` untuk perbaikan bug.
66
+ - `docs: ...` untuk perubahan dokumentasi.
67
+ - `chore: ...` untuk perubahan kecil (config, script).
68
+ - `refactor: ...` untuk perbaikan struktur kode tanpa mengubah fitur.
69
+
70
+ **Contoh:**
71
+ ```text
72
+ feat: add email validation rule to validator
73
+ fix: resolve EADDRINUSE error on windows
74
+ docs: update installation guide
75
+ ```
76
+
77
+ ## 📮 Mengirim Pull Request (PR)
78
+
79
+ 1. **Push** branch Anda ke GitHub:
80
+ ```bash
81
+ git push origin feature/nama-fitur
82
+ ```
83
+ 2. Buka repository fork Anda di GitHub, lalu klik **Compare & pull request**.
84
+ 3. Isi judul dan deskripsi PR dengan jelas:
85
+ - Jelaskan apa yang Anda ubah.
86
+ - Sertakan screenshot (jika ada perubahan visual/output).
87
+ - Referensikan Issue jika ada (contoh: `Closes #123`).
88
+ 4. Tunggu review dari maintainer. Kami mungkin akan meminta revisi kecil.
89
+ 5. Setelah disetujui, kode Anda akan di-merge! 🚀
90
+
91
+ ## 🐛 Melaporkan Bug (Issues)
92
+
93
+ Jika Anda menemukan bug tapi belum bisa memperbaikinya, silakan buat **Issue** baru.
94
+ - Gunakan judul yang jelas.
95
+ - Jelaskan langkah-langkah untuk mereproduksi bug (Steps to Reproduce).
96
+ - Sertakan log error atau screenshot.
97
+ - Sebutkan versi Node.js dan OS yang digunakan.
98
+
99
+ ## 💡 Ide & Diskusi
100
+
101
+ Punya ide fitur baru? Jangan ragu untuk membukanya di **GitHub Discussions** atau buat Issue dengan label `enhancement` sebelum mulai koding, agar kita bisa mendiskusikan desainnya terlebih dahulu.
102
+
103
+ ---
104
+
105
+ Selamat berkontribusi! Kode Anda akan membantu developer lain membangun aplikasi dengan lebih cepat dan menyenangkan. ❤️
@@ -0,0 +1,122 @@
1
+ # Deployment Guide
2
+
3
+ Panduan ini akan membantu Anda membawa aplikasi Lapeh dari `localhost` ke Server Production (VPS/Cloud).
4
+
5
+ ## Persiapan Pra-Deploy
6
+
7
+ Sebelum deploy, pastikan:
8
+
9
+ 1. **Environment Variables**: Siapkan nilai `.env` untuk production (DB URL asli, JWT Secret yang kuat).
10
+ 2. **Build**: TypeScript harus dikompilasi ke JavaScript.
11
+
12
+ ## Strategi 1: VPS (Ubuntu/Debian) dengan PM2
13
+
14
+ Ini adalah cara paling umum dan hemat biaya.
15
+
16
+ ### 1. Setup Server
17
+
18
+ Pastikan Node.js, NPM, dan Database (PostgreSQL/MySQL) sudah terinstall di server.
19
+
20
+ ### 2. Clone & Install
21
+
22
+ ```bash
23
+ git clone https://github.com/username/repo-anda.git
24
+ cd repo-anda
25
+ npm install --production=false # Install devDependencies juga untuk build
26
+ ```
27
+
28
+ ### 3. Build Aplikasi
29
+
30
+ ```bash
31
+ npm run build
32
+ ```
33
+
34
+ Ini akan menghasilkan folder `dist/`.
35
+
36
+ ### 4. Setup Database Production
37
+
38
+ ```bash
39
+ # Setup .env dulu
40
+ cp .env.example .env
41
+ nano .env # Isi dengan config production
42
+
43
+ # Jalankan migrasi (Hanya deploy schema, jangan reset!)
44
+ npm run prisma:deploy
45
+ ```
46
+
47
+ ### 5. Jalankan dengan PM2
48
+
49
+ Gunakan PM2 agar aplikasi jalan di background dan auto-restart jika crash.
50
+
51
+ ```bash
52
+ npm install -g pm2
53
+ npm run start:prod # Atau: pm2 start dist/src/index.js --name "api-lapeh"
54
+ ```
55
+
56
+ ### 6. Reverse Proxy (Nginx)
57
+
58
+ Jangan expose port 4000 langsung. Gunakan Nginx di depannya.
59
+ Config Nginx block:
60
+
61
+ ```nginx
62
+ server {
63
+ server_name api.domain-anda.com;
64
+ location / {
65
+ proxy_pass http://localhost:4000;
66
+ proxy_http_version 1.1;
67
+ proxy_set_header Upgrade $http_upgrade;
68
+ proxy_set_header Connection 'upgrade';
69
+ proxy_set_header Host $host;
70
+ proxy_cache_bypass $http_upgrade;
71
+ }
72
+ }
73
+ ```
74
+
75
+ ## Strategi 2: Docker (Container)
76
+
77
+ Lapeh sudah menyertakan `Dockerfile` (jika belum, buat sederhana saja).
78
+
79
+ **Dockerfile Minimal:**
80
+
81
+ ```dockerfile
82
+ FROM node:18-alpine
83
+
84
+ WORKDIR /app
85
+
86
+ COPY package*.json ./
87
+ RUN npm install
88
+
89
+ COPY . .
90
+ RUN npm run build
91
+
92
+ EXPOSE 4000
93
+ CMD ["npm", "run", "start:prod"]
94
+ ```
95
+
96
+ **Deploy:**
97
+
98
+ ```bash
99
+ docker build -t my-lapeh-app .
100
+ docker run -p 4000:4000 --env-file .env my-lapeh-app
101
+ ```
102
+
103
+ ## Strategi 3: PaaS (Railway / Render / Vercel)
104
+
105
+ Platform seperti Railway.app sangat mudah karena mendeteksi `package.json`.
106
+
107
+ 1. Push kode ke GitHub.
108
+ 2. Connect repo di Railway/Render.
109
+ 3. Set Environment Variables di dashboard mereka.
110
+ 4. Set **Build Command**: `npm run build`.
111
+ 5. Set **Start Command**: `npm run start:prod`.
112
+
113
+ **Catatan Khusus Vercel (Serverless):**
114
+ Lapeh didesain sebagai _Long-Running Server_ (Express). Deploy ke Vercel dimungkinkan tapi butuh wrapper serverless (seperti `vercel-express`). Untuk performa terbaik, disarankan menggunakan VPS atau Container (Railway/Fly.io).
115
+
116
+ ## Checklist Keamanan Production
117
+
118
+ - [ ] `NODE_ENV=production` harus diset.
119
+ - [ ] `JWT_SECRET` harus panjang dan acak.
120
+ - [ ] Database tidak boleh terekspos ke publik (gunakan private network atau firewall).
121
+ - [ ] Rate Limiting aktif (default Lapeh sudah aktif).
122
+ - [ ] Gunakan HTTPS (SSL) via Nginx atau Cloudflare.
package/doc/FAQ.md ADDED
@@ -0,0 +1,81 @@
1
+ # Frequently Asked Questions (FAQ)
2
+
3
+ Kumpulan pertanyaan umum dan solusi untuk masalah yang sering dihadapi.
4
+
5
+ ## Database
6
+
7
+ ### Q: Bagaimana cara mengganti database dari PostgreSQL ke MySQL?
8
+ **A:**
9
+ 1. Buka `prisma/base.prisma.template`.
10
+ 2. Ubah `provider = "postgresql"` menjadi `provider = "mysql"`.
11
+ 3. Di `.env`, ubah `DATABASE_URL` formatnya menjadi format MySQL (`mysql://user:pass@host:3306/db`).
12
+ 4. Hapus folder `prisma/migrations` (jika baru mulai) atau siapkan strategi migrasi.
13
+ 5. Jalankan `npm run prisma:migrate`.
14
+
15
+ ### Q: Bagaimana cara membuat relasi antar tabel?
16
+ **A:**
17
+ Definisikan relasi di file `.prisma` masing-masing. Karena file akan digabung, Anda bisa mereferensikan model yang ada di file lain.
18
+ **File `user.prisma`:**
19
+ ```prisma
20
+ model User {
21
+ id Int @id
22
+ posts Post[] // Relasi ke Post
23
+ }
24
+ ```
25
+ **File `post.prisma`:**
26
+ ```prisma
27
+ model Post {
28
+ id Int @id
29
+ authorId Int
30
+ author User @relation(fields: [authorId], references: [id]) // Relasi ke User
31
+ }
32
+ ```
33
+
34
+ ## Redis & Caching
35
+
36
+ ### Q: Saya tidak ingin pakai Redis di local, ribet installnya.
37
+ **A:**
38
+ Tenang, Lapeh otomatis mendeteksi jika Redis tidak berjalan dan akan menggunakan **In-Memory Mock** (simulasi Redis di RAM). Aplikasi tetap jalan normal tanpa error. Anda tidak perlu config apa-apa.
39
+
40
+ ### Q: Bagaimana cara clear cache Redis?
41
+ **A:**
42
+ Jika punya akses CLI Redis: `redis-cli FLUSHALL`.
43
+ Atau via kode:
44
+ ```typescript
45
+ import { redis } from "@/core/redis";
46
+ await redis.flushall();
47
+ ```
48
+
49
+ ## Fitur & Kustomisasi
50
+
51
+ ### Q: Bagaimana cara handle File Upload?
52
+ **A:**
53
+ Gunakan `multer`. Framework sudah menyiapkannya di `src/routes/auth.ts` sebagai contoh (upload avatar).
54
+ Anda bisa copy logic konfigurasi `multer` tersebut ke route lain.
55
+
56
+ ### Q: Bagaimana cara menambah middleware global baru?
57
+ **A:**
58
+ Buka `src/core/server.ts`. Di sana ada bagian `// Global Middlewares`. Tambahkan middleware Express Anda di situ:
59
+ ```typescript
60
+ app.use(myCustomMiddleware);
61
+ ```
62
+
63
+ ### Q: Saya ingin mengubah port server.
64
+ **A:**
65
+ Cukup ubah variabel `PORT` di file `.env`. Defaultnya adalah `4000`.
66
+
67
+ ## Troubleshooting
68
+
69
+ ### Q: Error `EADDRINUSE: address already in use :::4000`
70
+ **A:**
71
+ Artinya port 4000 sedang dipakai program lain (atau instance Lapeh sebelumnya yang nyangkut).
72
+ **Solusi:**
73
+ 1. Matikan terminal.
74
+ 2. Jalankan perintah kill (framework biasanya memberi saran commandnya saat error muncul).
75
+ - Windows: `taskkill /F /IM node.exe` (Hati-hati ini mematikan semua node process).
76
+ - Atau cari PID nya: `netstat -ano | findstr :4000`.
77
+
78
+ ### Q: Error `Unique constraint failed` saat seeding
79
+ **A:**
80
+ Data yang mau dimasukkan sudah ada (misal email `sa@sa.com`).
81
+ Jalankan `npm run db:reset` untuk menghapus semua data dan mulai dari nol.
@@ -0,0 +1,165 @@
1
+ # Fitur & Konsep Inti
2
+
3
+ Dokumen ini menjelaskan fitur-fitur utama Lapeh Framework dan cara penggunaannya secara mendalam.
4
+
5
+ ## 1. Validasi Data (Laravel-Style)
6
+
7
+ Framework ini menyediakan utility `Validator` yang terinspirasi dari Laravel, menggunakan `zod` di belakang layar namun dengan API yang lebih string-based dan mudah dibaca.
8
+
9
+ **Lokasi:** `@/utils/validator`
10
+
11
+ ### Penggunaan Dasar
12
+
13
+ ```typescript
14
+ import { Validator } from "@/utils/validator";
15
+
16
+ export async function createProduct(req: Request, res: Response) {
17
+ const validator = await Validator.make(req.body, {
18
+ name: "required|string|min:3",
19
+ price: "required|number|min:1000",
20
+ email: "required|email|unique:user,email", // Cek unik di tabel user kolom email
21
+ category_id: "required|exists:category,id", // Cek exist di tabel category kolom id
22
+ photo: "required|image|max:2048", // Validasi file upload (Max 2MB)
23
+ });
24
+
25
+ if (validator.fails()) {
26
+ return sendError(res, 400, "Validation failed", validator.errors());
27
+ }
28
+
29
+ const data = validator.validated();
30
+ // Lanjut proses simpan...
31
+ }
32
+ ```
33
+
34
+ ### Aturan Tersedia (Rules)
35
+
36
+ - `required`: Wajib diisi.
37
+ - `string`, `number`, `boolean`: Tipe data.
38
+ - `email`: Format email valid.
39
+ - `min:X`, `max:X`: Panjang string atau nilai number.
40
+ - `unique:table,column`: Pastikan nilai belum ada di database (Async).
41
+ - `exists:table,column`: Pastikan nilai ada di database (Async).
42
+ - `image`: File harus berupa gambar (jpg, png, webp, dll).
43
+ - `mimes:types`: File harus tipe tertentu (misal: `mimes:pdf,docx`).
44
+
45
+ ## 2. High Performance Response (Fastify-Style)
46
+
47
+ Untuk endpoint yang membutuhkan performa tinggi (misalnya list data besar), gunakan serialisasi berbasis schema. Ini jauh lebih cepat daripada `res.json` standar Express.
48
+
49
+ **Lokasi:** `@/utils/response`, `@/core/serializer`
50
+
51
+ ### Langkah Implementasi
52
+
53
+ 1. **Definisikan Schema Output**
54
+ Sesuaikan dengan field yang ingin ditampilkan ke user.
55
+
56
+ ```typescript
57
+ const productSchema = {
58
+ type: "object",
59
+ properties: {
60
+ id: { type: "string" }, // BigInt otomatis jadi string
61
+ name: { type: "string" },
62
+ price: { type: "number" },
63
+ },
64
+ };
65
+ ```
66
+
67
+ 2. **Buat Serializer (Cached)**
68
+ Simpan di luar handler function agar dicompile sekali saja.
69
+
70
+ ```typescript
71
+ import { getSerializer, createResponseSchema } from "@/core/serializer";
72
+
73
+ const productSerializer = getSerializer(
74
+ "product-single",
75
+ createResponseSchema(productSchema)
76
+ );
77
+ ```
78
+
79
+ 3. **Kirim Response**
80
+
81
+ ```typescript
82
+ import { sendFastSuccess } from "@/utils/response";
83
+
84
+ // Di dalam controller
85
+ sendFastSuccess(res, 200, productSerializer, {
86
+ status: "success",
87
+ message: "Data retrieved",
88
+ data: productData,
89
+ });
90
+ ```
91
+
92
+ ## 3. Authentication & Authorization (RBAC)
93
+
94
+ Sistem autentikasi menggunakan JWT (JSON Web Token) dan mendukung Role-Based Access Control.
95
+
96
+ ### Middleware Auth
97
+
98
+ - `requireAuth`: Memastikan user login (mengirim header `Authorization: Bearer <token>`).
99
+ - `requireAdmin`: Memastikan user login DAN memiliki role `admin` atau `super_admin`.
100
+
101
+ **Contoh di Route:**
102
+
103
+ ```typescript
104
+ import { requireAuth, requireAdmin } from "@/middleware/auth";
105
+
106
+ router.get("/profile", requireAuth, getProfile); // Login only
107
+ router.delete("/users/:id", requireAuth, requireAdmin, deleteUser); // Admin only
108
+ ```
109
+
110
+ ### Helper RBAC (Role Based Access Control)
111
+
112
+ Anda bisa mengecek permission secara granular di dalam controller:
113
+
114
+ ```typescript
115
+ // (Contoh implementasi, logic ada di AuthController/RbacController)
116
+ if (req.user.role !== "manager") {
117
+ return sendError(res, 403, "Forbidden");
118
+ }
119
+ ```
120
+
121
+ ## 4. Caching & Redis
122
+
123
+ Framework ini memiliki integrasi Redis "Zero-Config".
124
+
125
+ - Jika `REDIS_URL` ada di `.env` dan server Redis berjalan, framework akan connect.
126
+ - Jika tidak ada atau gagal connect, framework otomatis fallback ke **In-Memory Mock**. Ini membuat development di local tidak wajib install Redis.
127
+
128
+ **Mengakses Redis:**
129
+
130
+ ```typescript
131
+ import { redis } from "@/core/redis";
132
+
133
+ // Set cache (1 jam)
134
+ await redis.set("my-key", "value", "EX", 3600);
135
+
136
+ // Get cache
137
+ const val = await redis.get("my-key");
138
+ ```
139
+
140
+ ## 5. Keamanan (Security)
141
+
142
+ Secara default, framework sudah menerapkan:
143
+
144
+ - **Helmet**: Mengamankan HTTP headers.
145
+ - **CORS**: Mengizinkan akses lintas domain (configurable).
146
+ - **Rate Limiting**: Membatasi jumlah request per IP untuk mencegah DDoS/Brute Force.
147
+ - Konfigurasi ada di `src/middleware/rateLimit.ts`.
148
+ - Default: 100 request / 15 menit.
149
+
150
+ ## 6. Import Path Aliases
151
+
152
+ Gunakan `@/` untuk import module agar kode lebih bersih.
153
+
154
+ - `@/core` -> `src/core`
155
+ - `@/controllers` -> `src/controllers`
156
+ - `@/utils` -> `src/utils`
157
+ - `@/middleware` -> `src/middleware`
158
+
159
+ **Contoh:**
160
+
161
+ ```typescript
162
+ import { prisma } from "@/core/database"; // ✅ Rapi
163
+ // vs
164
+ import { prisma } from "../../../core/database"; // ❌ Berantakan
165
+ ```