pub struct Request {
pub state: AppState,
pub session: Session,
pub token: CsrfToken,
pub user: Option<AuthUser>,
pub headers: HeaderMap,
pub extensions: Extensions,
pub uri: Uri,
pub params: HashMap<String, String>,
pub active_tx: Arc<Mutex<Option<Transaction>>>,
}Expand description
Request — Bundle Extractor untuk menyederhanakan Dependency Injection. Menyediakan akses cepat ke State, Session, CSRF, Path Params, Query Params, dan Helper Response dalam satu parameter.
Fields§
§state: AppState§session: Session§token: CsrfToken§user: Option<AuthUser>§headers: HeaderMap§extensions: Extensions§uri: Uri§params: HashMap<String, String>§active_tx: Arc<Mutex<Option<Transaction>>>Implementations§
Source§impl Request
impl Request
Sourcepub fn db(&self) -> &DatabasePool
pub fn db(&self) -> &DatabasePool
Shortcut untuk mengambil instance DatabasePool.
Sourcepub async fn begin_transaction(&self) -> Result<Transaction, AppError>
pub async fn begin_transaction(&self) -> Result<Transaction, AppError>
Mulai transaksi database baru (ACID Transaction) langsung dari Request. Sangat bersih, tanpa closure, tanpa tanda ‘|’, dan otomatis rollback jika gagal.
Sourcepub async fn table(
&self,
name: &'static str,
) -> Result<TableQueryBuilder, AppError>
pub async fn table( &self, name: &'static str, ) -> Result<TableQueryBuilder, AppError>
Akses TableQueryBuilder yang terikat pada transaksi kontekstual req.
Jika transaksi belum dimulai via req.begin(), transaksi akan otomatis diinisialisasi!
Contoh: req.table("accounts").await?.where_eq("id", 1).decrement("balance", 50000).await?;
Sourcepub async fn commit(&self) -> Result<(), AppError>
pub async fn commit(&self) -> Result<(), AppError>
Commit transaksi kontekstual yang sedang aktif pada request ini.
Sourcepub async fn rollback(&self) -> Result<(), AppError>
pub async fn rollback(&self) -> Result<(), AppError>
Batalkan transaksi kontekstual yang sedang aktif pada request ini.
Sourcepub async fn find(
&self,
table: &'static str,
id: i64,
) -> Result<Option<Value>, AppError>
pub async fn find( &self, table: &'static str, id: i64, ) -> Result<Option<Value>, AppError>
Cari satu baris data berdasarkan ID langsung dari request (Gaya 2: Contextual Request).
Sourcepub async fn begin(&self) -> Result<Transaction, AppError>
pub async fn begin(&self) -> Result<Transaction, AppError>
Alias ringkas untuk begin_transaction()
Sourcepub fn db_arc(&self) -> Arc<DatabasePool> ⓘ
pub fn db_arc(&self) -> Arc<DatabasePool> ⓘ
Shortcut untuk mengambil Arc
Sourcepub fn pg_pool(&self) -> Option<Pool<Postgres>>
pub fn pg_pool(&self) -> Option<Pool<Postgres>>
Akses direct native PgPool (PostgreSQL) jika fitur postgres aktif.
Sourcepub fn sqlite_pool(&self) -> Option<Pool<Sqlite>>
pub fn sqlite_pool(&self) -> Option<Pool<Sqlite>>
Akses direct native SqlitePool jika fitur sqlite aktif.
Sourcepub fn bearer_token(&self) -> Option<String>
pub fn bearer_token(&self) -> Option<String>
Ambil token Bearer dari header Authorization jika tersedia.
Sourcepub async fn revoke_token(&self) -> bool
pub async fn revoke_token(&self) -> bool
Cabut / batalkan (revoke) token JWT aktif saat ini (misal pada endpoint POST /api/logout).
Sourcepub fn queue(&self) -> &QueueManager
pub fn queue(&self) -> &QueueManager
Shortcut untuk mengakses Queue Manager
Sourcepub async fn dispatch(
&self,
job_name: &str,
payload: Value,
) -> Result<(), String>
pub async fn dispatch( &self, job_name: &str, payload: Value, ) -> Result<(), String>
Shortcut untuk dispatch background job
Sourcepub fn view(&self, template: &str) -> ViewBuilder
pub fn view(&self, template: &str) -> ViewBuilder
Shortcut untuk membuat instance ViewBuilder.
Sourcepub async fn session_get<T>(&self, key: &str) -> Option<T>where
T: DeserializeOwned,
pub async fn session_get<T>(&self, key: &str) -> Option<T>where
T: DeserializeOwned,
Shortcut untuk mengambil nilai dari session.
Sourcepub async fn session_set<T>(&self, key: &str, value: T)where
T: Serialize,
pub async fn session_set<T>(&self, key: &str, value: T)where
T: Serialize,
Shortcut untuk menyimpan nilai ke dalam session.
Sourcepub fn is_authenticated(&self) -> bool
pub fn is_authenticated(&self) -> bool
Cek apakah user sudah login.
Sourcepub fn can(&self, permission: &str) -> bool
pub fn can(&self, permission: &str) -> bool
Cek apakah user yang sedang login memiliki izin (Permission).
Sourcepub fn cannot(&self, permission: &str) -> bool
pub fn cannot(&self, permission: &str) -> bool
Cek apakah user tidak memiliki izin (Permission).
Otorisasi izin secara deklaratif di Controller. Mengembalikan Ok(()) jika diizinkan, atau Err(AppError::Forbidden) jika ditolak.
Otorisasi peran (Role) secara deklaratif di Controller.
Sourcepub fn audit_log(
&self,
action: &str,
resource: &str,
resource_id: Option<String>,
details: Option<Value>,
status: &str,
)
pub fn audit_log( &self, action: &str, resource: &str, resource_id: Option<String>, details: Option<Value>, status: &str, )
Catat log audit secara asinkron (Enterprise Audit Trail).
Sourcepub async fn redirect_if_authenticated(
&self,
path: &str,
) -> Option<Response<Body>>
pub async fn redirect_if_authenticated( &self, path: &str, ) -> Option<Response<Body>>
Redirect jika user sudah login (misal: di halaman login/register).
Sourcepub fn header(&self, name: &str) -> Option<&str>
pub fn header(&self, name: &str) -> Option<&str>
Mengambil nilai header HTTP sebagai string slice.
Sourcepub fn wants_json(&self) -> bool
pub fn wants_json(&self) -> bool
Cek apakah client meminta response berformat JSON (ala Laravel $request->wantsJson()). Memeriksa header Accept untuk ‘application/json’ atau ‘/’.
Sourcepub fn is_json(&self) -> bool
pub fn is_json(&self) -> bool
Cek apakah request payload bertipe JSON (Content-Type: application/json).
Sourcepub fn param(&self, key: &str) -> Option<&str>
pub fn param(&self, key: &str) -> Option<&str>
Ambil nilai path parameter (misal: :id pada route /api/contacts/:id).
Sourcepub fn param_as<T>(&self, key: &str) -> Option<T>where
T: FromStr,
pub fn param_as<T>(&self, key: &str) -> Option<T>where
T: FromStr,
Ambil nilai path parameter dan parse ke tipe data tujuan.
Sourcepub fn id_or_fail(&self) -> Result<i64, AppError>
pub fn id_or_fail(&self) -> Result<i64, AppError>
Ambil ID dari route parameter atau kembalikan AppError::BadRequest jika tidak ada atau tidak valid.
Sourcepub fn query_val(&self, key: &str) -> Option<String>
pub fn query_val(&self, key: &str) -> Option<String>
Ambil nilai query string berdasarkan nama key (misal: ?search=budi).
Sourcepub fn per_page(&self, default_per_page: usize) -> usize
pub fn per_page(&self, default_per_page: usize) -> usize
Ambil jumlah per halaman dari query parameter ?per_page=X atau ?limit=X (default: default_per_page).
Sourcepub fn pagination(&self) -> (usize, usize)
pub fn pagination(&self) -> (usize, usize)
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).
Sourcepub fn query<T>(&self) -> Result<T, AppError>where
T: DeserializeOwned,
pub fn query<T>(&self) -> Result<T, AppError>where
T: DeserializeOwned,
Deserialize seluruh query string ke dalam struct bertipe T.
Sourcepub fn json<T>(&self, value: T) -> Result<Response<Body>, AppError>where
T: Serialize,
pub fn json<T>(&self, value: T) -> Result<Response<Body>, AppError>where
T: Serialize,
Shortcut untuk mengembalikan JSON response secara instan.
Sourcepub fn ok<T>(&self, data: T) -> Result<Response<Body>, AppError>where
T: Serialize,
pub fn ok<T>(&self, data: T) -> Result<Response<Body>, AppError>where
T: Serialize,
Mengembalikan response JSON standar HTTP 200 OK:
{ "success": true, "data": ... }
Sourcepub fn success<T>(
&self,
data: T,
message: &str,
) -> Result<Response<Body>, AppError>where
T: Serialize,
pub fn success<T>(
&self,
data: T,
message: &str,
) -> Result<Response<Body>, AppError>where
T: Serialize,
Mengembalikan response JSON HTTP 200 OK dengan pesan sukses kustom:
{ "success": true, "message": "...", "data": ... }
Sourcepub fn created<T>(&self, data: T) -> Result<Response<Body>, AppError>where
T: Serialize,
pub fn created<T>(&self, data: T) -> Result<Response<Body>, AppError>where
T: Serialize,
Mengembalikan response JSON HTTP 201 Created:
{ "success": true, "data": ... }
Sourcepub fn created_with<T>(
&self,
data: T,
message: &str,
) -> Result<Response<Body>, AppError>where
T: Serialize,
pub fn created_with<T>(
&self,
data: T,
message: &str,
) -> Result<Response<Body>, AppError>where
T: Serialize,
Mengembalikan response JSON HTTP 201 Created dengan pesan:
Sourcepub fn no_content(&self) -> Result<Response<Body>, AppError>
pub fn no_content(&self) -> Result<Response<Body>, AppError>
Mengembalikan response HTTP 204 No Content
Sourcepub fn not_found(&self, message: &str) -> Result<Response<Body>, AppError>
pub fn not_found(&self, message: &str) -> Result<Response<Body>, AppError>
Mengembalikan response JSON HTTP 404 Not Found:
{ "success": false, "error": "..." }
Sourcepub fn bad_request(&self, message: &str) -> Result<Response<Body>, AppError>
pub fn bad_request(&self, message: &str) -> Result<Response<Body>, AppError>
Mengembalikan response JSON HTTP 400 Bad Request:
{ "success": false, "error": "..." }
Mengembalikan response JSON HTTP 401 Unauthorized
Sourcepub fn forbidden(&self, message: &str) -> Result<Response<Body>, AppError>
pub fn forbidden(&self, message: &str) -> Result<Response<Body>, AppError>
Mengembalikan response JSON HTTP 403 Forbidden
Sourcepub fn unprocessable<E>(
&self,
errors: E,
message: &str,
) -> Result<Response<Body>, AppError>where
E: Serialize,
pub fn unprocessable<E>(
&self,
errors: E,
message: &str,
) -> Result<Response<Body>, AppError>where
E: Serialize,
Mengembalikan response JSON HTTP 422 Unprocessable Entity (Validasi error)
Sourcepub fn paginate<T>(
&self,
paginator: LengthAwarePaginator<T>,
) -> Result<Response<Body>, AppError>where
T: Serialize,
pub fn paginate<T>(
&self,
paginator: LengthAwarePaginator<T>,
) -> Result<Response<Body>, AppError>where
T: Serialize,
Mengembalikan response JSON data paginasi bergaya Laravel:
{ "success": true, "data": [...], "meta": { "total": ..., "current_page": ..., "last_page": ..., "per_page": ... } }
Trait Implementations§
Source§impl<S> FromRequestParts<S> for Request
impl<S> FromRequestParts<S> for Request
Source§type Rejection = AppError
type Rejection = AppError
Source§fn from_request_parts<'life0, 'life1, 'async_trait>(
parts: &'life0 mut Parts,
state: &'life1 S,
) -> Pin<Box<dyn Future<Output = Result<Request, <Request as FromRequestParts<S>>::Rejection>> + Send + 'async_trait>>where
'life0: 'async_trait,
'life1: 'async_trait,
Request: 'async_trait,
fn from_request_parts<'life0, 'life1, 'async_trait>(
parts: &'life0 mut Parts,
state: &'life1 S,
) -> Pin<Box<dyn Future<Output = Result<Request, <Request as FromRequestParts<S>>::Rejection>> + Send + 'async_trait>>where
'life0: 'async_trait,
'life1: 'async_trait,
Request: 'async_trait,
Auto Trait Implementations§
impl !Freeze for Request
impl !RefUnwindSafe for Request
impl !UnwindSafe for Request
impl Forget for Request
impl Move for Request
impl Send for Request
impl Sync for Request
impl Unpin for Request
impl UnsafeUnpin for Request
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<S, T> FromRequest<S, ViaParts> for T
impl<S, T> FromRequest<S, ViaParts> for T
Source§type Rejection = <T as FromRequestParts<S>>::Rejection
type Rejection = <T as FromRequestParts<S>>::Rejection
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more