#http-request #leptos #deserialize #serialization #response #requests #error

bin+lib leptos_reqwest

为使用 reqwest 进行 HTTP 请求并在您的 Leptos 项目中处理响应提供实用程序

5 个版本

0.1.4 2024 年 5 月 29 日
0.1.3 2024 年 5 月 29 日
0.1.2 2024 年 5 月 29 日
0.1.1 2024 年 5 月 29 日
0.1.0 2024 年 5 月 19 日

#860 in 解析实现

MIT 许可证

19KB
251

leptos_reqwest

为使用 reqwest 进行 HTTP 请求并在您的 Leptos 项目中处理响应提供实用程序

示例

use leptos::SerializationError;
use leptos_reqwest::{send_and_parse, HttpMethod, LeptosReqwestError};
use reqwest::{header, Error};
use serde::{Serialize, Deserialize};

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CustomErrors {
    pub errors: Vec<CustomError>,
}
impl LeptosReqwestError for CustomErrors {
    fn deserialization_error(e: SerializationError) -> Self {
        CustomErrors {
            errors: vec![CustomError {message: e.to_string(), extensions: ErrorExtension { code: String::from("500"), reason: None }}],
        }
    }

    fn read_error(e: Error) -> Self {
        CustomErrors {
            errors: vec![CustomError {message: e.to_string(), extensions: ErrorExtension { code: String::from("500"), reason: None }}],
        }
    }
}
impl Default for CustomErrors {
    fn default() -> Self {
        CustomErrors {
            errors: vec![CustomError {message: String::from("System Error"), extensions: ErrorExtension { code: String::from("500"), reason: None }}],
        }
    }
}
#[derive(Debug, Clone, Deserialize, Default, Serialize)]
pub struct CustomError {
    pub message: String,
    pub extensions: ErrorExtension,
}
#[derive(Debug, Clone, Deserialize, Default, Serialize)]
pub struct ErrorExtension {
    pub code: String,
    pub reason: Option<String>
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct AuthenticationRequest {
    pub email: String,
    pub password: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthenticationResponse {
    pub data: AuthenticationResponsePayload,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthenticationResponsePayload {
    pub expires: u64,
    pub refresh_token: String,
    pub access_token: String,
}
#[tokio::main]
async fn main() {
    let url = String::from("http:://example.com");

        let request = AuthenticationRequest {
            email: String::from("[email protected]"),
            password: String::from("********"),
        };

        let headers = header::HeaderMap::new();

        let send = send_and_parse::<AuthenticationRequest, AuthenticationResponse, CustomErrors>(Some(request), url, headers, HttpMethod::Post).await;
        match send {
            Ok(response) => {
                println!("{:#?}", response);
            },
            Err(e) => {
                println!("{:#?}", e);
            }
        }
}

路线图

  • 添加处理超时的功能

依赖项

~21–34MB
~552K SLoC