lapeh 2.2.1 โ 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.
- package/doc/CHANGELOG.md +38 -0
- package/doc/CHEATSHEET.md +89 -0
- package/doc/CLI.md +106 -0
- package/doc/CONTRIBUTING.md +105 -0
- package/doc/DEPLOYMENT.md +122 -0
- package/doc/FAQ.md +81 -0
- package/doc/FEATURES.md +165 -0
- package/doc/GETTING_STARTED.md +108 -0
- package/doc/INTRODUCTION.md +60 -0
- package/doc/PACKAGES.md +66 -0
- package/doc/PERFORMANCE.md +91 -0
- package/doc/ROADMAP.md +93 -0
- package/doc/SECURITY.md +93 -0
- package/doc/STRUCTURE.md +72 -0
- package/doc/TUTORIAL.md +192 -0
- package/eslint.config.mjs +26 -0
- package/framework.md +168 -113
- package/nodemon.json +1 -1
- package/package.json +12 -3
- package/prisma/seed.ts +0 -1
- package/readme.md +46 -0
- package/src/controllers/authController.ts +145 -39
- package/src/controllers/petController.ts +70 -16
- package/src/controllers/rbacController.ts +82 -9
- package/src/core/redis.ts +5 -4
- package/src/core/serializer.ts +63 -0
- package/src/middleware/auth.ts +0 -1
- package/src/middleware/rateLimit.ts +1 -1
- package/src/routes/auth.ts +3 -3
- package/src/utils/response.ts +21 -0
- package/tsconfig.json +17 -12
- package/document.md +0 -205
package/doc/FEATURES.md
ADDED
|
@@ -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
|
+
```
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Getting Started with Lapeh Framework
|
|
2
|
+
|
|
3
|
+
Selamat datang di dokumentasi resmi **Lapeh Framework**. Panduan ini akan membantu Anda memulai instalasi, konfigurasi, dan pemahaman dasar tentang struktur proyek.
|
|
4
|
+
|
|
5
|
+
## Persyaratan Sistem
|
|
6
|
+
|
|
7
|
+
Sebelum memulai, pastikan sistem Anda memenuhi persyaratan berikut:
|
|
8
|
+
|
|
9
|
+
- **Node.js**: Versi 18.x atau lebih baru.
|
|
10
|
+
- **Database**: PostgreSQL (Recommended) atau MySQL/MariaDB.
|
|
11
|
+
- **Package Manager**: NPM (bawaan Node.js).
|
|
12
|
+
|
|
13
|
+
## Instalasi
|
|
14
|
+
|
|
15
|
+
Cara termudah untuk memulai adalah menggunakan CLI generator `npx`.
|
|
16
|
+
|
|
17
|
+
### 1. Buat Project Baru
|
|
18
|
+
|
|
19
|
+
Jalankan perintah berikut di terminal Anda:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npx lapeh@latest nama-project-anda
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Atau untuk setup lengkap (dengan data dummy user & role):
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npx lapeh@latest nama-project-anda --full
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### 2. Setup Awal
|
|
32
|
+
|
|
33
|
+
Setelah project dibuat, masuk ke direktori project dan jalankan setup wizard:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
cd nama-project-anda
|
|
37
|
+
npm run first
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Script ini akan melakukan hal-hal berikut secara otomatis:
|
|
41
|
+
|
|
42
|
+
1. Menyalin `.env.example` ke `.env`.
|
|
43
|
+
2. Menginstall semua dependency (`npm install`).
|
|
44
|
+
3. Membuat **JWT Secret** yang aman.
|
|
45
|
+
4. Menjalankan migrasi database (membuat tabel).
|
|
46
|
+
5. Menjalankan seeder (mengisi data awal).
|
|
47
|
+
|
|
48
|
+
### 3. Jalankan Server Development
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
npm run dev
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Server akan berjalan di `http://localhost:4000` (atau port yang Anda tentukan di `.env`).
|
|
55
|
+
|
|
56
|
+
## Struktur Direktori
|
|
57
|
+
|
|
58
|
+
Berikut adalah struktur folder standar Lapeh Framework:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
my-app/
|
|
62
|
+
โโโ bin/ # Script CLI untuk npx
|
|
63
|
+
โโโ doc/ # Dokumentasi proyek
|
|
64
|
+
โโโ prisma/ # Konfigurasi Database & Schema
|
|
65
|
+
โ โโโ migrations/ # File history migrasi database
|
|
66
|
+
โ โโโ base.prisma.template # Template konfigurasi database
|
|
67
|
+
โ โโโ schema.prisma # File schema gabungan (Auto-generated)
|
|
68
|
+
โ โโโ seed.ts # Script untuk mengisi data awal
|
|
69
|
+
โโโ scripts/ # Script utility (Generator, Compiler)
|
|
70
|
+
โโโ src/ # Source code utama aplikasi
|
|
71
|
+
โ โโโ controllers/ # Logika bisnis (Handler request)
|
|
72
|
+
โ โโโ core/ # Konfigurasi inti (DB, Redis, Server)
|
|
73
|
+
โ โโโ middleware/ # Middleware Express (Auth, RateLimit)
|
|
74
|
+
โ โโโ models/ # Definisi Schema Prisma per-fitur
|
|
75
|
+
โ โโโ routes/ # Definisi routing API
|
|
76
|
+
โ โโโ utils/ # Helper function (Response, Validator)
|
|
77
|
+
โ โโโ index.ts # Entry point aplikasi
|
|
78
|
+
โโโ .env # Variabel lingkungan (Rahasia)
|
|
79
|
+
โโโ package.json # Dependensi & Script NPM
|
|
80
|
+
โโโ tsconfig.json # Konfigurasi TypeScript
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Konfigurasi Environment (.env)
|
|
84
|
+
|
|
85
|
+
File `.env` menyimpan konfigurasi penting. Berikut adalah variabel kunci:
|
|
86
|
+
|
|
87
|
+
```ini
|
|
88
|
+
# Server
|
|
89
|
+
PORT=4000
|
|
90
|
+
NODE_ENV=development
|
|
91
|
+
|
|
92
|
+
# Database (Ganti sesuai kredensial Anda)
|
|
93
|
+
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
|
|
94
|
+
|
|
95
|
+
# Security
|
|
96
|
+
JWT_SECRET="rahasia-super-panjang-dan-acak"
|
|
97
|
+
ACCESS_TOKEN_EXPIRES_IN=3600 # 1 jam
|
|
98
|
+
|
|
99
|
+
# Redis (Opsional - otomatis mock jika tidak ada)
|
|
100
|
+
REDIS_URL="redis://localhost:6379"
|
|
101
|
+
NO_REDIS=false # Set true untuk memaksa mode mock
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Langkah Selanjutnya
|
|
105
|
+
|
|
106
|
+
- Pelajari cara menggunakan **[CLI Tools](CLI.md)** untuk mempercepat development.
|
|
107
|
+
- Pahami **[Fitur & Konsep Inti](FEATURES.md)** framework.
|
|
108
|
+
- Ikuti **[Tutorial Studi Kasus](TUTORIAL.md)** untuk membangun fitur nyata.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Pengenalan Lapeh Framework
|
|
2
|
+
|
|
3
|
+
## Apa itu Lapeh?
|
|
4
|
+
|
|
5
|
+
**Lapeh** adalah framework Backend untuk Node.js yang dibangun di atas **Express** dan **TypeScript**.
|
|
6
|
+
|
|
7
|
+
Jika Anda pernah menggunakan **Laravel** (PHP) atau **NestJS** (Node.js), Anda akan merasa sangat familiar. Lapeh mengambil filosofi kemudahan & struktur rapi dari Laravel, namun tetap mempertahankan fleksibilitas dan kecepatan Express.
|
|
8
|
+
|
|
9
|
+
Nama "Lapeh" diambil dari bahasa Minang yang berarti "Lepas" atau "Bebas", melambangkan kebebasan developer untuk membangun aplikasi dengan cepat tanpa terbebani konfigurasi yang rumit.
|
|
10
|
+
|
|
11
|
+
## Mengapa Lapeh Dibuat?
|
|
12
|
+
|
|
13
|
+
Di ekosistem Node.js, developer sering mengalami "Decision Fatigue" (Kelelahan memilih):
|
|
14
|
+
- "Pakai ORM apa? Prisma, TypeORM, atau Drizzle?"
|
|
15
|
+
- "Validasi pakai Joi, Zod, atau express-validator?"
|
|
16
|
+
- "Struktur foldernya gimana? MVC? Clean Architecture?"
|
|
17
|
+
- "Auth-nya gimana?"
|
|
18
|
+
|
|
19
|
+
Lapeh menjawab semua itu dengan **Opinionated Defaults**:
|
|
20
|
+
1. **ORM**: Prisma (Standar industri saat ini).
|
|
21
|
+
2. **Validasi**: Zod (dengan wrapper syntax ala Laravel).
|
|
22
|
+
3. **Struktur**: MVC Modular (Controller, Model, Route terpisah tapi kohesif).
|
|
23
|
+
4. **Auth**: JWT + RBAC (Role Based Access Control) siap pakai.
|
|
24
|
+
|
|
25
|
+
## Perbandingan dengan Framework Lain
|
|
26
|
+
|
|
27
|
+
| Fitur | Express (Raw) | NestJS | Lapeh Framework |
|
|
28
|
+
| :--- | :--- | :--- | :--- |
|
|
29
|
+
| **Learning Curve** | Rendah (tapi bingung struktur) | Tinggi (Angular-style, Decorators) | **Sedang** (Express + Struktur Jelas) |
|
|
30
|
+
| **Boilerplate** | Kosong | Sangat Banyak | **Pas (Ready to use)** |
|
|
31
|
+
| **Type Safety** | Manual | Strict | **Strict (TypeScript Native)** |
|
|
32
|
+
| **Kecepatan Dev** | Lambat (setup manual) | Sedang | **Cepat (CLI Generator)** |
|
|
33
|
+
| **Fleksibilitas** | Sangat Tinggi | Kaku | **Tinggi** |
|
|
34
|
+
|
|
35
|
+
## Filosofi "The Lapeh Way"
|
|
36
|
+
|
|
37
|
+
1. **Developer Experience (DX) First**: CLI tools, error message yang jelas, dan hot-reload adalah prioritas.
|
|
38
|
+
2. **Performance by Default**: Serialisasi JSON cepat (Fastify-style) dan Redis caching terintegrasi.
|
|
39
|
+
3. **Explicit is Better than Implicit**: Tidak ada "sihir" yang terlalu gelap. Kode controller Anda adalah kode Express biasa yang Anda mengerti.
|
|
40
|
+
4. **Production Ready**: Security (Helmet, Rate Limit) dan Scalability (Docker, Cluster) bukan pikiran belakangan, tapi bawaan.
|
|
41
|
+
|
|
42
|
+
## Siklus Hidup Request (Request Lifecycle)
|
|
43
|
+
|
|
44
|
+
Bagaimana Lapeh menangani satu permintaan dari user?
|
|
45
|
+
|
|
46
|
+
1. **Request Masuk** (`GET /api/users`)
|
|
47
|
+
2. **Security Middleware**: Helmet (Headers), CORS, Rate Limiter.
|
|
48
|
+
3. **Global Middleware**: Request Logger, Body Parser (JSON).
|
|
49
|
+
4. **Routing**: Mencocokkan URL di `src/routes/`.
|
|
50
|
+
5. **Auth Middleware** (Opsional): Cek token JWT & Role.
|
|
51
|
+
6. **Validator** (Opsional): Validasi input body/query.
|
|
52
|
+
7. **Controller**: Logika bisnis utama dijalankan.
|
|
53
|
+
- Panggil Database (Prisma).
|
|
54
|
+
- Panggil Cache (Redis).
|
|
55
|
+
8. **Serializer**: Data diformat & disanitasi (misal: hide password).
|
|
56
|
+
9. **Response**: JSON dikirim kembali ke user.
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
**Selanjutnya:** Pelajari struktur folder di [Struktur Proyek](STRUCTURE.md).
|
package/doc/PACKAGES.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Referensi Package & Dependencies
|
|
2
|
+
|
|
3
|
+
Dokumen ini menjelaskan fungsi dari setiap library (package) yang terinstall di Lapeh Framework, sehingga Anda mengerti kegunaan "alat-alat" yang ada di dalam kotak peralatan Anda.
|
|
4
|
+
|
|
5
|
+
## Core Framework (Fondasi)
|
|
6
|
+
|
|
7
|
+
Package-package ini adalah nyawa dari framework ini.
|
|
8
|
+
|
|
9
|
+
| Package | Deskripsi | Kenapa Kita Pakai? |
|
|
10
|
+
| :--- | :--- | :--- |
|
|
11
|
+
| **`express`** | Web Framework untuk Node.js. | Standar industri, ringan, dan komunitasnya terbesar. |
|
|
12
|
+
| **`dotenv`** | Memuat variabel dari file `.env`. | Agar konfigurasi rahasia (DB password, API Key) tidak di-hardcode. |
|
|
13
|
+
| **`cors`** | Cross-Origin Resource Sharing. | Mengizinkan frontend (React/Vue) dari domain berbeda untuk mengakses API kita. |
|
|
14
|
+
| **`helmet`** | Middleware keamanan HTTP headers. | Melindungi aplikasi dari serangan umum (XSS, Clickjacking) dengan mengatur header HTTP secara otomatis. |
|
|
15
|
+
|
|
16
|
+
## Database & ORM
|
|
17
|
+
|
|
18
|
+
| Package | Deskripsi | Kenapa Kita Pakai? |
|
|
19
|
+
| :--- | :--- | :--- |
|
|
20
|
+
| **`@prisma/client`** | Query builder & ORM. | Type-safe query database. Autocomplete-nya sangat membantu developer. |
|
|
21
|
+
| **`pg`** | Driver PostgreSQL. | Driver native untuk koneksi ke database Postgres. |
|
|
22
|
+
| **`@prisma/adapter-*`** | Adapter serverless. | (Opsional) Persiapan untuk deployment ke environment serverless (seperti Vercel/Neon). |
|
|
23
|
+
|
|
24
|
+
## Authentication & Security
|
|
25
|
+
|
|
26
|
+
| Package | Deskripsi | Kenapa Kita Pakai? |
|
|
27
|
+
| :--- | :--- | :--- |
|
|
28
|
+
| **`jsonwebtoken`** | Implementasi JWT. | Standar token untuk autentikasi stateless (API). |
|
|
29
|
+
| **`bcryptjs`** | Hashing password. | Mengamankan password user di database (satu arah). |
|
|
30
|
+
| **`express-rate-limit`** | Pembatas request. | Mencegah serangan DDoS ringan atau Brute Force login. |
|
|
31
|
+
|
|
32
|
+
## Utilities & Helper
|
|
33
|
+
|
|
34
|
+
| Package | Deskripsi | Kenapa Kita Pakai? |
|
|
35
|
+
| :--- | :--- | :--- |
|
|
36
|
+
| **`zod`** | Schema validation library. | Memvalidasi input user (req.body) dengan syntax yang kuat dan mudah dibaca. |
|
|
37
|
+
| **`fast-json-stringify`** | Serializer JSON cepat. | Mengubah object ke JSON string 2x-3x lebih cepat dari `JSON.stringify` bawaan. |
|
|
38
|
+
| **`uuid`** | Generator ID unik. | Membuat string acak unik (UUID v4). |
|
|
39
|
+
| **`slugify`** | String formatter. | Mengubah "Judul Artikel Keren" menjadi `judul-artikel-keren` (URL friendly). |
|
|
40
|
+
| **`multer`** | Middleware upload file. | Menangani `multipart/form-data` untuk upload gambar/dokumen. |
|
|
41
|
+
| **`winston`** | Logger library. | Mencatat log aplikasi (error/info) ke file atau console dengan format rapi. |
|
|
42
|
+
|
|
43
|
+
## Realtime & Caching
|
|
44
|
+
|
|
45
|
+
| Package | Deskripsi | Kenapa Kita Pakai? |
|
|
46
|
+
| :--- | :--- | :--- |
|
|
47
|
+
| **`socket.io`** | Library WebSocket. | Fitur komunikasi real-time dua arah (chat, notifikasi live). |
|
|
48
|
+
| **`ioredis`** | Client Redis yang robust. | Driver terbaik untuk Redis di Node.js. |
|
|
49
|
+
| **`ioredis-mock`** | Simulasi Redis di memori. | Memungkinkan development tanpa perlu install Redis server asli (sangat berguna untuk pemula). |
|
|
50
|
+
|
|
51
|
+
## Development Tools (DevDependencies)
|
|
52
|
+
|
|
53
|
+
Package ini hanya dipakai saat koding, tidak ikut terinstall di server production.
|
|
54
|
+
|
|
55
|
+
| Package | Deskripsi | Fungsi |
|
|
56
|
+
| :--- | :--- | :--- |
|
|
57
|
+
| **`typescript`** | Compiler TS. | Mengubah kode `.ts` menjadi `.js`. |
|
|
58
|
+
| **`nodemon`** | Auto-restarter. | Restart server otomatis setiap kita save file. |
|
|
59
|
+
| **`eslint`** | Linter (Polisi Kode). | Mencari potensi error dan variabel yang tidak terpakai. |
|
|
60
|
+
| **`@types/*`** | Definisi Tipe. | Memberikan intellisense (saran kode) untuk library JavaScript biasa. |
|
|
61
|
+
| **`prisma`** | Prisma CLI. | Alat untuk migrasi database (`prisma migrate`) dan generate client. |
|
|
62
|
+
| **`tsc-alias`** | Path resolver. | Mengubah alias `@/core` menjadi path relatif `../core` saat build production. |
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
Dengan memahami daftar ini, Anda tahu persis apa yang terjadi di balik layar aplikasi Anda. Tidak ada "Bloatware", setiap package punya tujuan spesifik.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Panduan Performa & Skalabilitas Lapeh Framework
|
|
2
|
+
|
|
3
|
+
Dokumen ini menjelaskan cara memaksimalkan performa aplikasi Lapeh Anda menggunakan fitur-fitur canggih seperti Fast-Serialization dan Clustering.
|
|
4
|
+
|
|
5
|
+
## 1. High Performance Serialization (Fastify-Style)
|
|
6
|
+
|
|
7
|
+
Express secara default menggunakan `JSON.stringify()` yang lambat karena harus memeriksa tipe data setiap field secara runtime. Lapeh mengadopsi teknik **Schema Based Serialization** (seperti Fastify) yang bisa meningkatkan throughput JSON hingga **2x-3x lipat**.
|
|
8
|
+
|
|
9
|
+
### Cara Penggunaan
|
|
10
|
+
|
|
11
|
+
Gunakan `sendFastSuccess` di controller Anda untuk endpoint yang membutuhkan performa tinggi (misalnya: list data yang besar).
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { Request, Response } from "express";
|
|
15
|
+
import { getSerializer, createResponseSchema } from "../core/serializer";
|
|
16
|
+
import { sendFastSuccess } from "../utils/response";
|
|
17
|
+
|
|
18
|
+
// 1. Definisikan Schema Output (JSON Schema Standard)
|
|
19
|
+
const userSchema = {
|
|
20
|
+
type: "object",
|
|
21
|
+
properties: {
|
|
22
|
+
id: { type: "integer" },
|
|
23
|
+
name: { type: "string" },
|
|
24
|
+
email: { type: "string" },
|
|
25
|
+
// Password tidak dimasukkan, jadi otomatis tidak akan terkirim (aman!)
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// 2. Compile Serializer (Otomatis dicache oleh framework)
|
|
30
|
+
const userListSerializer = getSerializer("user-list", createResponseSchema({
|
|
31
|
+
type: "array",
|
|
32
|
+
items: userSchema
|
|
33
|
+
}));
|
|
34
|
+
|
|
35
|
+
export async function getUsers(req: Request, res: Response) {
|
|
36
|
+
const users = await prisma.users.findMany();
|
|
37
|
+
|
|
38
|
+
// 3. Kirim response super cepat
|
|
39
|
+
return sendFastSuccess(res, 200, userListSerializer, {
|
|
40
|
+
status: "success",
|
|
41
|
+
message: "Data fetched",
|
|
42
|
+
data: users
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 2. Horizontal Scaling (Load Balancer & Cluster)
|
|
50
|
+
|
|
51
|
+
Lapeh dirancang untuk siap di-scale secara horizontal (menambah jumlah server, bukan memperbesar spesifikasi server).
|
|
52
|
+
|
|
53
|
+
### Arsitektur Cluster
|
|
54
|
+
- **Nginx**: Bertindak sebagai Load Balancer yang membagi trafik ke server-server aplikasi.
|
|
55
|
+
- **Redis**: Menyimpan Session, Rate Limit, dan Cache agar bisa diakses oleh semua server (Shared State).
|
|
56
|
+
- **App Instances**: Beberapa instance aplikasi Lapeh yang berjalan paralel.
|
|
57
|
+
|
|
58
|
+
### Cara Menjalankan Cluster (Docker)
|
|
59
|
+
|
|
60
|
+
Kami telah menyediakan konfigurasi siap pakai di `docker-compose.cluster.yml`.
|
|
61
|
+
|
|
62
|
+
1. **Build & Run Cluster**:
|
|
63
|
+
```bash
|
|
64
|
+
docker-compose -f docker-compose.cluster.yml up --build
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
2. **Akses Aplikasi**:
|
|
68
|
+
Buka `http://localhost:8080`.
|
|
69
|
+
Nginx akan otomatis membagi request Anda ke `app-1` atau `app-2`.
|
|
70
|
+
|
|
71
|
+
3. **Cek Status**:
|
|
72
|
+
```bash
|
|
73
|
+
docker-compose -f docker-compose.cluster.yml ps
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Konfigurasi Rate Limiter Terdistribusi
|
|
77
|
+
Middleware `src/middleware/rateLimit.ts` telah diupdate untuk menggunakan Redis Store.
|
|
78
|
+
Ini artinya jika User A terkena limit di Server 1, dia juga akan terblokir di Server 2.
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
// src/middleware/rateLimit.ts
|
|
82
|
+
store: redis ? new RedisStore({ sendCommand: ... }) : undefined
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## 3. Tips Optimasi Lainnya
|
|
88
|
+
|
|
89
|
+
- **Gunakan `.lean()` / Select**: Saat query database, selalu pilih field yang dibutuhkan saja.
|
|
90
|
+
- **Compression**: Aktifkan gzip/brotli di Nginx (sudah ada di config default Nginx umumnya).
|
|
91
|
+
- **Keep-Alive**: Gunakan koneksi database yang persistent (sudah dihandle oleh Prisma).
|
package/doc/ROADMAP.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# Roadmap & Future Requests (Rencana Pengembangan)
|
|
2
|
+
|
|
3
|
+
Dokumen ini berisi daftar fitur yang direncanakan untuk membuat **Lapeh Framework** setara dengan framework backend enterprise lainnya (seperti NestJS, Laravel, atau Django).
|
|
4
|
+
|
|
5
|
+
Ini adalah **Undangan Terbuka** bagi para kontributor! Jika Anda tertarik mengerjakan salah satu fitur di bawah ini, silakan buat Issue/PR.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## ๐๏ธ Core & Architecture
|
|
10
|
+
|
|
11
|
+
### 1. Dependency Injection (DI) Container
|
|
12
|
+
* **Tujuan**: Membuat kode lebih testable dan modular.
|
|
13
|
+
* **Konsep**: Saat ini Lapeh menggunakan pendekatan import langsung. Implementasi DI sederhana (seperti `InversifyJS` atau custom container) akan memudahkan unit testing dan decoupling.
|
|
14
|
+
* **Inspirasi**: NestJS Providers, Angular DI.
|
|
15
|
+
|
|
16
|
+
### 2. Event Emitter (Pub/Sub)
|
|
17
|
+
* **Tujuan**: Decoupling logic antar modul.
|
|
18
|
+
* **Contoh**: Saat user register -> Emit event `UserRegistered` -> Listener `SendWelcomeEmail` & `CreateWallet` berjalan terpisah.
|
|
19
|
+
* **Status**: Belum ada (bisa pakai `eventemitter3`).
|
|
20
|
+
|
|
21
|
+
### 3. API Documentation Generator (Swagger/OpenAPI)
|
|
22
|
+
* **Tujuan**: Auto-generate dokumentasi API interaktif.
|
|
23
|
+
* **Rencana**: Membaca file route dan validator schema, lalu men-generate spesifikasi Swagger UI secara otomatis di `/api/docs`.
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## ๐ ๏ธ Fitur Enterprise (The "Missing" Parts)
|
|
28
|
+
|
|
29
|
+
### 4. Job Queues & Background Workers
|
|
30
|
+
* **Tujuan**: Memproses tugas berat di background agar tidak memblokir HTTP request.
|
|
31
|
+
* **Teknologi**: Integrasi dengan **BullMQ** (Redis).
|
|
32
|
+
* **Fitur**:
|
|
33
|
+
* Decorators/Helpers untuk mendefinisikan Job.
|
|
34
|
+
* Dashboard monitoring job (seperti Horizon di Laravel).
|
|
35
|
+
* Retry mechanism & Failed job handling.
|
|
36
|
+
|
|
37
|
+
### 5. Task Scheduling (Cron Jobs)
|
|
38
|
+
* **Tujuan**: Menjalankan tugas berkala (misal: "Kirim rekap email setiap jam 12 malam").
|
|
39
|
+
* **Rencana**: Wrapper di atas `node-cron` yang terintegrasi dengan struktur framework.
|
|
40
|
+
* **CLI**: `npm run schedule:run`.
|
|
41
|
+
|
|
42
|
+
### 6. Storage Abstraction Layer
|
|
43
|
+
* **Tujuan**: Satu interface untuk upload file ke berbagai provider (Local, AWS S3, Google Cloud Storage, MinIO).
|
|
44
|
+
* **Konsep**:
|
|
45
|
+
```typescript
|
|
46
|
+
// Tidak peduli drivernya apa, kodenya sama:
|
|
47
|
+
await Storage.disk('s3').put('avatars/1.jpg', fileBuffer);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### 7. Mailer Service
|
|
51
|
+
* **Tujuan**: Standarisasi pengiriman email.
|
|
52
|
+
* **Fitur**:
|
|
53
|
+
* Support SMTP, Mailgun, SES.
|
|
54
|
+
* Support Template Engine (Handlebars/EJS) untuk body email.
|
|
55
|
+
* Queue integration (kirim email di background).
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## ๐งช Testing & Quality Assurance
|
|
60
|
+
|
|
61
|
+
### 8. Native Testing Suite
|
|
62
|
+
* **Tujuan**: Memudahkan user menulis test.
|
|
63
|
+
* **Rencana**:
|
|
64
|
+
* Integrasi **Vitest** atau **Jest** pre-configured.
|
|
65
|
+
* Helper untuk HTTP Testing (supertest wrapper).
|
|
66
|
+
* Helper untuk Database Transaction (rollback setelah test selesai).
|
|
67
|
+
* Command: `npm run test`, `npm run make:test`.
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## ๐ Globalization & Security
|
|
72
|
+
|
|
73
|
+
### 9. Localization (i18n)
|
|
74
|
+
* **Tujuan**: Mendukung respon API dalam berbagai bahasa.
|
|
75
|
+
* **Fitur**: Mendeteksi header `Accept-Language` dan mengembalikan pesan error/success sesuai bahasa user.
|
|
76
|
+
|
|
77
|
+
### 10. API Versioning
|
|
78
|
+
* **Tujuan**: Mendukung multiple versi API (v1, v2) tanpa merusak klien lama.
|
|
79
|
+
* **Rencana**: Routing strategy berbasis URL prefix (`/api/v1/...`) atau Header.
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## ๐ป CLI Enhancements
|
|
84
|
+
|
|
85
|
+
### 11. Interactive CLI (TUI)
|
|
86
|
+
* **Tujuan**: Membuat CLI lebih user friendly.
|
|
87
|
+
* **Ide**: Saat menjalankan `npx lapeh`, muncul menu interaktif untuk memilih fitur yang mau diinstall (pilih DB, pilih mau pakai Redis atau tidak, dll).
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Tertarik Berkontribusi?
|
|
92
|
+
|
|
93
|
+
Pilih salah satu topik di atas, buat Issue di GitHub dengan judul `[Proposal] Nama Fitur`, dan mari kita diskusikan cara implementasinya! ๐
|
package/doc/SECURITY.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# Security Best Practices (Panduan Keamanan)
|
|
2
|
+
|
|
3
|
+
Keamanan bukan fitur tambahan, melainkan prioritas utama. Lapeh Framework sudah dikonfigurasi dengan standar keamanan yang baik (Secure by Default), namun Anda tetap perlu memahami cara menjaga aplikasi tetap aman.
|
|
4
|
+
|
|
5
|
+
## 1. Perlindungan Bawaan (Built-in Protection)
|
|
6
|
+
|
|
7
|
+
Secara default, Lapeh sudah mengaktifkan:
|
|
8
|
+
|
|
9
|
+
### Helmet (HTTP Headers)
|
|
10
|
+
|
|
11
|
+
Mengamankan aplikasi dari serangan umum web vulnerabilities dengan mengatur HTTP headers yang tepat.
|
|
12
|
+
|
|
13
|
+
- **XSS Filter**: Aktif.
|
|
14
|
+
- **Frameguard**: Mencegah Clickjacking.
|
|
15
|
+
- **HSTS**: Memaksa browser menggunakan HTTPS (di production).
|
|
16
|
+
|
|
17
|
+
### Rate Limiting
|
|
18
|
+
|
|
19
|
+
Mencegah serangan _Brute Force_ dan _DDoS_ sederhana.
|
|
20
|
+
|
|
21
|
+
- **Default**: 100 request per 15 menit per IP.
|
|
22
|
+
- **Lokasi Config**: `src/middleware/rateLimit.ts`.
|
|
23
|
+
|
|
24
|
+
### CORS (Cross-Origin Resource Sharing)
|
|
25
|
+
|
|
26
|
+
Mengontrol domain mana yang boleh mengakses API Anda.
|
|
27
|
+
|
|
28
|
+
- **Lokasi Config**: `src/core/server.ts`.
|
|
29
|
+
- **Saran**: Di production, ubah `origin: "*"` menjadi domain frontend spesifik Anda (misal `origin: "https://frontend-anda.com"`).
|
|
30
|
+
|
|
31
|
+
## 2. Praktik Terbaik Developer
|
|
32
|
+
|
|
33
|
+
Framework tidak bisa melindungi dari kode yang buruk. Berikut hal yang WAJIB Anda lakukan:
|
|
34
|
+
|
|
35
|
+
### a. Validasi Input (Wajib!)
|
|
36
|
+
|
|
37
|
+
Jangan pernah mempercayai input user. Selalu gunakan `Validator`.
|
|
38
|
+
|
|
39
|
+
**โ Tidak Aman (Raw Query):**
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
// Bahaya SQL Injection jika pakai raw query manual (walau Prisma aman, tetap hati-hati)
|
|
43
|
+
const user =
|
|
44
|
+
await prisma.$queryRaw`SELECT * FROM users WHERE email = ${req.body.email}`;
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**โ
Aman (Validator + Prisma Client):**
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
const valid = await Validator.make(req.body, { email: "required|email" });
|
|
51
|
+
// Prisma Client otomatis sanitize input
|
|
52
|
+
const user = await prisma.user.findUnique({
|
|
53
|
+
where: { email: valid.validated().email },
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### b. Manajemen Password
|
|
58
|
+
|
|
59
|
+
- **Hashing**: Jangan pernah simpan password plain text. Gunakan `bcryptjs` (sudah terintegrasi di AuthController).
|
|
60
|
+
- **Strength**: Validasi password minimal 8 karakter.
|
|
61
|
+
```typescript
|
|
62
|
+
password: "required|string|min:8";
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### c. JWT & Session
|
|
66
|
+
|
|
67
|
+
- **Secret Key**: Pastikan `JWT_SECRET` di `.env` adalah string acak yang panjang (32+ karakter).
|
|
68
|
+
- **Expiration**: Token akses (`ACCESS_TOKEN_EXPIRES_IN`) sebaiknya pendek (misal 15 menit - 1 jam). Gunakan Refresh Token (fitur roadmap) untuk sesi panjang.
|
|
69
|
+
|
|
70
|
+
### d. Error Handling
|
|
71
|
+
|
|
72
|
+
Jangan pernah mengekspos detail error sistem (stack trace) ke user di Production.
|
|
73
|
+
|
|
74
|
+
**โ Buruk:**
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
res.status(500).json({ error: err.message, stack: err.stack }); // Hacker bisa lihat struktur folder server
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
**โ
Aman (Lapeh Default):**
|
|
81
|
+
Lapeh sudah menangani ini. Di mode `production`, error internal hanya akan menampilkan "Internal Server Error" tanpa detail sensitif.
|
|
82
|
+
|
|
83
|
+
## 3. Checklist Sebelum Deploy
|
|
84
|
+
|
|
85
|
+
- [ ] Pastikan `NODE_ENV=production` di server.
|
|
86
|
+
- [ ] Ganti `JWT_SECRET` default dengan yang baru (`npm run generate:jwt`).
|
|
87
|
+
- [ ] Batasi CORS origin hanya ke domain frontend Anda.
|
|
88
|
+
- [ ] Pastikan database tidak bisa diakses publik (gunakan firewall/private IP).
|
|
89
|
+
- [ ] Gunakan HTTPS (SSL/TLS). API tanpa HTTPS sangat mudah disadap.
|
|
90
|
+
|
|
91
|
+
## 4. Melaporkan Celah Keamanan
|
|
92
|
+
|
|
93
|
+
Jika Anda menemukan celah keamanan di framework ini, mohon **JANGAN** buat Issue publik. Kirim email langsung ke maintainer (lihat `package.json`) agar bisa diperbaiki (patched) sebelum diexploitasi orang jahat.
|