1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use crate::core::application::AppState;
use crate::core::auth::AuthUser;
use crate::core::error::AppError;
use axum::{async_trait, extract::FromRequestParts, http::request::Parts};
use axum_csrf::CsrfToken;
use std::collections::HashMap;
use tower_sessions::Session;
/// Type alias untuk controller handler return type yang cantik dan ekspresif.
/// Menggantikan `Result<impl IntoResponse, AppError>` menjadi hanya `LuminaResult`.
pub type LuminaResult<T = axum::response::Response> = std::result::Result<T, AppError>;
/// Alias alternatif untuk LuminaResult.
pub type HttpResult<T = axum::response::Response> = LuminaResult<T>;
/// Request — Bundle Extractor untuk menyederhanakan Dependency Injection.
/// Menyediakan akses cepat ke State, Session, CSRF, Path Params, Query Params, dan Helper Response dalam satu parameter.
pub struct Request {
pub state: AppState,
pub session: Session,
pub token: CsrfToken,
pub user: Option<AuthUser>,
pub headers: axum::http::HeaderMap,
pub extensions: axum::http::Extensions,
pub uri: axum::http::Uri,
pub params: HashMap<String, String>,
}
#[async_trait]
impl<S> FromRequestParts<S> for Request
where
AppState: FromRef<S>,
S: Send + Sync,
{
type Rejection = crate::core::error::AppError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let app_state = AppState::from_ref(state);
let session = parts
.extensions
.get::<Session>()
.cloned()
.ok_or(crate::core::error::AppError::InternalServerError)?;
let token = CsrfToken::from_request_parts(parts, state)
.await
.map_err(|_| crate::core::error::AppError::InternalServerError)?;
// Cek user dari extension (Middleware) atau Session
let user = parts
.extensions
.get::<AuthUser>()
.cloned()
.or(session.get::<AuthUser>("user").await.unwrap_or_default());
let uri = parts.uri.clone();
let params = match axum::extract::RawPathParams::from_request_parts(parts, state).await {
Ok(raw) => raw
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect::<HashMap<String, String>>(),
Err(_) => HashMap::new(),
};
Ok(Self {
state: app_state,
session,
token,
user,
headers: parts.headers.clone(),
extensions: parts.extensions.clone(),
uri,
params,
})
}
}
use axum::extract::FromRef;
impl Request {
/// Shortcut untuk mengambil instance DatabasePool.
pub fn db(&self) -> &crate::database::connection::DatabasePool {
self.state.db()
}
/// Shortcut untuk mengambil Arc<DatabasePool>.
pub fn db_arc(&self) -> std::sync::Arc<crate::database::connection::DatabasePool> {
self.state
.db
.as_ref()
.expect("Database connection is not available")
.clone()
}
/// Shortcut untuk mengambil user yang sedang login.
pub fn user(&self) -> Option<crate::core::auth::AuthUser> {
self.user.clone()
}
/// Shortcut untuk membuat instance ViewBuilder.
pub fn view(&self, template: &str) -> crate::core::view::ViewBuilder {
crate::core::view::View::make(template)
}
/// Shortcut untuk membuat instance Redirect.
pub fn redirect(&self, path: &str) -> crate::core::response::Redirect {
crate::core::response::Redirect::to(path)
}
/// Shortcut untuk redirect kembali ke halaman asal (Referer).
pub fn back(&self) -> crate::core::response::Redirect {
let referer = self
.headers
.get(axum::http::header::REFERER)
.and_then(|h| h.to_str().ok())
.unwrap_or("/");
crate::core::response::Redirect::to(referer)
}
/// Shortcut untuk mengambil nilai dari session.
pub async fn session_get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.session.get::<T>(key).await.unwrap_or_default()
}
/// Shortcut untuk menyimpan nilai ke dalam session.
pub async fn session_set<T: serde::Serialize>(&self, key: &str, value: T) {
let _ = self.session.insert(key, value).await;
}
/// Shortcut untuk mengambil instance StorageManager.
pub fn storage(&self) -> &crate::core::storage::Storage {
&self.state.storage
}
/// Shortcut untuk mengambil instance Mailer.
pub fn mail(&self) -> &crate::core::mail::Mail {
&self.state.mail
}
/// Cek apakah user sudah login.
pub fn is_authenticated(&self) -> bool {
self.user.is_some()
}
/// Cek apakah user belum login (guest).
pub fn is_guest(&self) -> bool {
self.user.is_none()
}
/// Redirect jika user sudah login (misal: di halaman login/register).
pub async fn redirect_if_authenticated(&self, path: &str) -> Option<axum::response::Response> {
if self.is_authenticated() {
use axum::response::IntoResponse;
return Some(self.redirect(path).go(self).await.into_response());
}
None
}
/// Mengambil nilai header HTTP sebagai string slice.
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.get(name).and_then(|v| v.to_str().ok())
}
/// Cek apakah client meminta response berformat JSON (ala Laravel $request->wantsJson()).
/// Memeriksa header Accept untuk 'application/json' atau '*/*'.
pub fn wants_json(&self) -> bool {
if let Some(accept) = self.header("accept") {
accept.contains("application/json")
} else {
false
}
}
/// Cek apakah request payload bertipe JSON (Content-Type: application/json).
pub fn is_json(&self) -> bool {
if let Some(content_type) = self.header("content-type") {
content_type.contains("application/json")
} else {
false
}
}
// ─────────────────────────────────────────────────────────────────────────
// PARAMETER & QUERY HELPERS (ALA LARAVEL $request->...)
// ─────────────────────────────────────────────────────────────────────────
/// Ambil nilai path parameter (misal: :id pada route /api/contacts/:id).
pub fn param(&self, key: &str) -> Option<&str> {
self.params.get(key).map(|s| s.as_str())
}
/// Ambil nilai path parameter dan parse ke tipe data tujuan.
pub fn param_as<T: std::str::FromStr>(&self, key: &str) -> Option<T> {
self.param(key).and_then(|s| s.parse::<T>().ok())
}
/// Shortcut untuk mengambil ID dari route parameter (misal: :id).
pub fn id(&self) -> Option<i64> {
self.param_as::<i64>("id")
}
/// Ambil ID dari route parameter atau kembalikan AppError::BadRequest jika tidak ada atau tidak valid.
pub fn id_or_fail(&self) -> Result<i64, AppError> {
self.id().ok_or_else(|| AppError::BadRequest("Parameter ID wajib diberikan dan harus angka".to_string()))
}
/// Ambil nilai query string berdasarkan nama key (misal: ?search=budi).
pub fn query_val(&self, key: &str) -> Option<String> {
let q = self.uri.query()?;
for pair in q.split('&') {
let mut parts = pair.splitn(2, '=');
if let Some(k) = parts.next() {
if k == key {
let v = parts.next().unwrap_or("");
let decoded = v.replace('+', " ");
return Some(decoded);
}
}
}
None
}
/// Ambil nomor halaman dari query parameter `?page=X` (default: 1).
pub fn page(&self) -> usize {
self.query_val("page")
.and_then(|v| v.parse::<usize>().ok())
.unwrap_or(1)
.max(1)
}
/// Ambil jumlah per halaman dari query parameter `?per_page=X` atau `?limit=X` (default: default_per_page).
pub fn per_page(&self, default_per_page: usize) -> usize {
self.query_val("per_page")
.or_else(|| self.query_val("limit"))
.and_then(|v| v.parse::<usize>().ok())
.unwrap_or(default_per_page)
.max(1)
}
/// Shortcut mengambil tuple (page, per_page) untuk paginasi instan ala Laravel.
/// Default per_page adalah 10 jika tidak ditentukan di URL (?page=1&per_page=10).
pub fn pagination(&self) -> (usize, usize) {
(self.page(), self.per_page(10))
}
/// Deserialize seluruh query string ke dalam struct bertipe T.
pub fn query<T: serde::de::DeserializeOwned>(&self) -> Result<T, AppError> {
let q = self.uri.query().unwrap_or("");
serde_urlencoded::from_str(q).map_err(|e| AppError::BadRequest(format!("Format query parameter tidak valid: {}", e)))
}
// ─────────────────────────────────────────────────────────────────────────
// RESPONSE HELPERS (MENGEMBALIKAN LuminaResult / Ok(Response))
// ─────────────────────────────────────────────────────────────────────────
/// Shortcut untuk mengembalikan JSON response secara instan.
pub fn json<T: serde::Serialize>(&self, value: T) -> LuminaResult {
use axum::response::IntoResponse;
Ok(axum::Json(value).into_response())
}
/// Mengembalikan response JSON standar HTTP 200 OK:
/// `{ "success": true, "data": ... }`
pub fn ok<T: serde::Serialize>(&self, data: T) -> LuminaResult {
use axum::response::IntoResponse;
Ok(axum::Json(serde_json::json!({
"success": true,
"data": data
})).into_response())
}
/// Mengembalikan response JSON HTTP 200 OK dengan pesan sukses kustom:
/// `{ "success": true, "message": "...", "data": ... }`
pub fn success<T: serde::Serialize>(&self, data: T, message: &str) -> LuminaResult {
use axum::response::IntoResponse;
Ok(axum::Json(serde_json::json!({
"success": true,
"message": message,
"data": data
})).into_response())
}
/// Mengembalikan response JSON HTTP 201 Created:
/// `{ "success": true, "data": ... }`
pub fn created<T: serde::Serialize>(&self, data: T) -> LuminaResult {
use axum::response::IntoResponse;
Ok((
axum::http::StatusCode::CREATED,
axum::Json(serde_json::json!({
"success": true,
"data": data
}))
).into_response())
}
/// Mengembalikan response JSON HTTP 201 Created dengan pesan:
pub fn created_with<T: serde::Serialize>(&self, data: T, message: &str) -> LuminaResult {
use axum::response::IntoResponse;
Ok((
axum::http::StatusCode::CREATED,
axum::Json(serde_json::json!({
"success": true,
"message": message,
"data": data
}))
).into_response())
}
/// Mengembalikan response HTTP 204 No Content
pub fn no_content(&self) -> LuminaResult {
use axum::response::IntoResponse;
Ok(axum::http::StatusCode::NO_CONTENT.into_response())
}
/// Mengembalikan response JSON HTTP 404 Not Found:
/// `{ "success": false, "error": "..." }`
pub fn not_found(&self, message: &str) -> LuminaResult {
use axum::response::IntoResponse;
Ok((
axum::http::StatusCode::NOT_FOUND,
axum::Json(serde_json::json!({
"success": false,
"error": message
}))
).into_response())
}
/// Mengembalikan response JSON HTTP 400 Bad Request:
/// `{ "success": false, "error": "..." }`
pub fn bad_request(&self, message: &str) -> LuminaResult {
use axum::response::IntoResponse;
Ok((
axum::http::StatusCode::BAD_REQUEST,
axum::Json(serde_json::json!({
"success": false,
"error": message
}))
).into_response())
}
/// Mengembalikan response JSON HTTP 401 Unauthorized
pub fn unauthorized(&self, message: &str) -> LuminaResult {
use axum::response::IntoResponse;
Ok((
axum::http::StatusCode::UNAUTHORIZED,
axum::Json(serde_json::json!({
"success": false,
"error": message
}))
).into_response())
}
/// Mengembalikan response JSON HTTP 403 Forbidden
pub fn forbidden(&self, message: &str) -> LuminaResult {
use axum::response::IntoResponse;
Ok((
axum::http::StatusCode::FORBIDDEN,
axum::Json(serde_json::json!({
"success": false,
"error": message
}))
).into_response())
}
/// Mengembalikan response JSON HTTP 422 Unprocessable Entity (Validasi error)
pub fn unprocessable<E: serde::Serialize>(&self, errors: E, message: &str) -> LuminaResult {
use axum::response::IntoResponse;
Ok((
axum::http::StatusCode::UNPROCESSABLE_ENTITY,
axum::Json(serde_json::json!({
"success": false,
"message": message,
"errors": errors
}))
).into_response())
}
/// Mengembalikan response JSON data paginasi bergaya Laravel:
/// `{ "success": true, "data": [...], "meta": { "total": ..., "current_page": ..., "last_page": ..., "per_page": ... } }`
pub fn paginate<T: serde::Serialize>(&self, paginator: crate::database::orm::LengthAwarePaginator<T>) -> LuminaResult {
use axum::response::IntoResponse;
Ok(axum::Json(serde_json::json!({
"success": true,
"data": paginator.items,
"meta": {
"total": paginator.total,
"current_page": paginator.current_page,
"last_page": paginator.last_page,
"per_page": paginator.per_page
}
})).into_response())
}
}