Skip to main content

Request

Struct Request 

Source
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

Source

pub fn db(&self) -> &DatabasePool

Shortcut untuk mengambil instance DatabasePool.

Source

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.

Source

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?;

Source

pub async fn commit(&self) -> Result<(), AppError>

Commit transaksi kontekstual yang sedang aktif pada request ini.

Source

pub async fn rollback(&self) -> Result<(), AppError>

Batalkan transaksi kontekstual yang sedang aktif pada request ini.

Source

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).

Source

pub async fn begin(&self) -> Result<Transaction, AppError>

Alias ringkas untuk begin_transaction()

Source

pub fn db_arc(&self) -> Arc<DatabasePool> ⓘ

Shortcut untuk mengambil Arc.

Source

pub fn pg_pool(&self) -> Option<Pool<Postgres>>

Akses direct native PgPool (PostgreSQL) jika fitur postgres aktif.

Source

pub fn sqlite_pool(&self) -> Option<Pool<Sqlite>>

Akses direct native SqlitePool jika fitur sqlite aktif.

Source

pub fn bearer_token(&self) -> Option<String>

Ambil token Bearer dari header Authorization jika tersedia.

Source

pub async fn revoke_token(&self) -> bool

Cabut / batalkan (revoke) token JWT aktif saat ini (misal pada endpoint POST /api/logout).

Source

pub fn user(&self) -> Option<AuthUser>

Shortcut untuk mengambil user yang sedang login.

Source

pub fn queue(&self) -> &QueueManager

Shortcut untuk mengakses Queue Manager

Source

pub async fn dispatch( &self, job_name: &str, payload: Value, ) -> Result<(), String>

Shortcut untuk dispatch background job

Source

pub fn view(&self, template: &str) -> ViewBuilder

Shortcut untuk membuat instance ViewBuilder.

Source

pub fn redirect(&self, path: &str) -> Redirect

Shortcut untuk membuat instance Redirect.

Source

pub fn back(&self) -> Redirect

Shortcut untuk redirect kembali ke halaman asal (Referer).

Source

pub async fn session_get<T>(&self, key: &str) -> Option<T>

Shortcut untuk mengambil nilai dari session.

Source

pub async fn session_set<T>(&self, key: &str, value: T)
where T: Serialize,

Shortcut untuk menyimpan nilai ke dalam session.

Source

pub fn storage(&self) -> &Storage

Shortcut untuk mengambil instance StorageManager.

Source

pub fn mail(&self) -> &Mail

Shortcut untuk mengambil instance Mailer.

Source

pub fn is_authenticated(&self) -> bool

Cek apakah user sudah login.

Source

pub fn is_guest(&self) -> bool

Cek apakah user belum login (guest).

Source

pub fn can(&self, permission: &str) -> bool

Cek apakah user yang sedang login memiliki izin (Permission).

Source

pub fn cannot(&self, permission: &str) -> bool

Cek apakah user tidak memiliki izin (Permission).

Source

pub fn has_role(&self, role: &str) -> bool

Cek apakah user memiliki peran (Role).

Source

pub fn authorize(&self, permission: &str) -> Result<(), AppError>

Otorisasi izin secara deklaratif di Controller. Mengembalikan Ok(()) jika diizinkan, atau Err(AppError::Forbidden) jika ditolak.

Source

pub fn authorize_role(&self, role: &str) -> Result<(), AppError>

Otorisasi peran (Role) secara deklaratif di Controller.

Source

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).

Source

pub async fn redirect_if_authenticated( &self, path: &str, ) -> Option<Response<Body>>

Redirect jika user sudah login (misal: di halaman login/register).

Source

pub fn header(&self, name: &str) -> Option<&str>

Mengambil nilai header HTTP sebagai string slice.

Source

pub fn wants_json(&self) -> bool

Cek apakah client meminta response berformat JSON (ala Laravel $request->wantsJson()). Memeriksa header Accept untuk ‘application/json’ atau ‘/’.

Source

pub fn is_json(&self) -> bool

Cek apakah request payload bertipe JSON (Content-Type: application/json).

Source

pub fn param(&self, key: &str) -> Option<&str>

Ambil nilai path parameter (misal: :id pada route /api/contacts/:id).

Source

pub fn param_as<T>(&self, key: &str) -> Option<T>
where T: FromStr,

Ambil nilai path parameter dan parse ke tipe data tujuan.

Source

pub fn id(&self) -> Option<i64>

Shortcut untuk mengambil ID dari route parameter (misal: :id).

Source

pub fn id_or_fail(&self) -> Result<i64, AppError>

Ambil ID dari route parameter atau kembalikan AppError::BadRequest jika tidak ada atau tidak valid.

Source

pub fn query_val(&self, key: &str) -> Option<String>

Ambil nilai query string berdasarkan nama key (misal: ?search=budi).

Source

pub fn page(&self) -> usize

Ambil nomor halaman dari query parameter ?page=X (default: 1).

Source

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).

Source

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).

Source

pub fn query<T>(&self) -> Result<T, AppError>

Deserialize seluruh query string ke dalam struct bertipe T.

Source

pub fn json<T>(&self, value: T) -> Result<Response<Body>, AppError>
where T: Serialize,

Shortcut untuk mengembalikan JSON response secara instan.

Source

pub fn ok<T>(&self, data: T) -> Result<Response<Body>, AppError>
where T: Serialize,

Mengembalikan response JSON standar HTTP 200 OK: { "success": true, "data": ... }

Source

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": ... }

Source

pub fn created<T>(&self, data: T) -> Result<Response<Body>, AppError>
where T: Serialize,

Mengembalikan response JSON HTTP 201 Created: { "success": true, "data": ... }

Source

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:

Source

pub fn no_content(&self) -> Result<Response<Body>, AppError>

Mengembalikan response HTTP 204 No Content

Source

pub fn not_found(&self, message: &str) -> Result<Response<Body>, AppError>

Mengembalikan response JSON HTTP 404 Not Found: { "success": false, "error": "..." }

Source

pub fn bad_request(&self, message: &str) -> Result<Response<Body>, AppError>

Mengembalikan response JSON HTTP 400 Bad Request: { "success": false, "error": "..." }

Source

pub fn unauthorized(&self, message: &str) -> Result<Response<Body>, AppError>

Mengembalikan response JSON HTTP 401 Unauthorized

Source

pub fn forbidden(&self, message: &str) -> Result<Response<Body>, AppError>

Mengembalikan response JSON HTTP 403 Forbidden

Source

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)

Source

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
where AppState: FromRef<S>, S: Send + Sync,

Source§

type Rejection = AppError

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
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,

Perform the extraction.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Source§

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request<'life0, 'async_trait>( req: Request<Body>, state: &'life0 S, ) -> Pin<Box<dyn Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>> + Send + 'async_trait>>
where 'life0: 'async_trait, T: 'async_trait,

Perform the extraction.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more