- 
                Notifications
    
You must be signed in to change notification settings  - Fork 1
 
Home
        Andrey edited this page Jan 31, 2025 
        ·
        5 revisions
      
    Welcome to the my-http-server-swagger wiki!
- method: "GET", "POST", "PUT", "DELETE" etc.
 - route = route of request.
 - description - goes to swagger;
 - controller - goes to swagger;
 - input_data - optional - model with input request data (struct marked with #[derive(MyHttpInput)]);
 - result - array of elements {status_code: 200, description: "Ok response", model: "CryptoDepositAddressesResponse"}
- model - is optional
 
 
With input data
#[my_http_server_swagger::http_route(
    method: "GET",
    route: "/api/generate",
    description: "Generate crypto deposit address",
    controller: "CryptoDeposit",
    input_data: "GetCryptoDepositAddressRequest",
    result:[
        {status_code: 200, description: "Ok response", model: "CryptoDepositAddressesResponse"},
    ]
)]
pub struct GetCryptoDepositAddressesAction {
    app: Arc<AppContext>,
}
impl GetCryptoDepositAddressesAction {
    pub fn new(app: Arc<AppContext>) -> Self {
        Self { app }
    }
}
async fn handle_request(
    action: &GetCryptoDepositAddressesAction,
    input_data: GetCryptoDepositAddressRequest,
    ctx: &HttpContext,
) -> Result<HttpOkResult, HttpFailResult> {
   todo!("Implement);
}Without input data
#[my_http_server_swagger::http_route(
    method: "GET",
    route: "/api/generate",
    description: "Generate crypto deposit address",
    controller: "CryptoDeposit",
    result:[
        {status_code: 200, description: "Ok response", model: "CryptoDepositAddressesResponse"},
    ]
)]
pub struct GetCryptoDepositAddressesAction {
    app: Arc<AppContext>,
}
impl GetCryptoDepositAddressesAction {
    pub fn new(app: Arc<AppContext>) -> Self {
        Self { app }
    }
}
async fn handle_request(
    action: &GetCryptoDepositAddressesAction,
    ctx: &HttpContext,
) -> Result<HttpOkResult, HttpFailResult> {
   todo!("Implement);
}field attributes can enable serialization of data from:
- http_query;
 - http_header;
 - http_form - parameter of http_form goes into the field market with http_form attribute;
 - http_path - path segment goes into the field market with http_path attribute;
 - http_body - whole body goes to the field marked with http_body attribute. Can be used one time per http input model;
 - http_body_type - is used - to specify type of body if we use http_body attribute;
 
General Example:
#[derive(MyHttpInput)]
pub struct BulkDeleteInputContract {
    #[http_query(name = "tableName"; description = "Name of a table")]
    pub table_name: String,
    #[http_query(name = "syncPeriod"; description = "Synchronization period"; default="Sec5")]
    pub sync_period: DataSynchronizationPeriod,
    #[http_body(
        description = "PartitionToDelete1:[RowToDelete1, RowToDelete2, RowToDelete3],[PartitionToDelete1]:[RowToDelete1, RowToDelete2, RowToDelete3]"
    )]
    pub body: Vec<u8>,
}#[derive(MyHttpInput)]
pub struct GetRowInputModel {
    #[http_query(name = "tableName"; description = "Name of a table")]
    pub table_name: String,
    #[http_query(name = "partitionKey"; description = "Partition Key")]
    pub partition_key: Option<String>,
    #[http_query(name = "rowKey"; description = "Row Key")]
    pub row_key: Option<String>,
    #[http_query(name = "limit"; description = "Limit amount of records we are going to get")]
    pub limit: Option<usize>,
    #[http_query(name = "skip"; description = "Skip amount of records before start collecting them")]
    pub skip: Option<usize>,
    #[http_header(name ="setPartitionExpirationTime" description = "Set Partition Expiration time")]
    pub set_partition_expiration_time: Option<String>,
    #[http_header(name ="setRowsExpirationTime" description = "Set Found DbRows Expiration time")]
    pub set_db_rows_expiration_time: Option<String>,
}#[derive(MyHttpInput)]
pub struct InsertOrReplaceInputContract {
    #[http_query(name = "tableName"; description = "Name of a table")]
    pub table_name: String,
    #[http_query(name = "syncPeriod"; description = "Synchronization period"; default="Sec5")]
    pub sync_period: DataSynchronizationPeriod,
    #[http_body(description = "DbEntity description"; body_type="BaseDbRowContract")]
    pub body: Vec<u8>,
}
#[derive(Serialize, Deserialize, Debug, MyHttpObjectStructure)]
pub struct BaseDbRowContract {
    #[serde(rename = "partitionKey")]
    pub partition_key: String,
    #[serde(rename = "rowKey")]
    pub row_key: String,
    #[serde(rename = "timeStamp")]
    pub time_stamp: String,
    pub expires: Option<String>,
}Enum Example:
attires fiels:
- default flag can be used to specify the param;
 - value - can override creating from str parameter;
 - id - number id of the enum case;
 - description - is description
 
#[derive(Clone, Copy, MyHttpStringEnum)]
pub enum DataSynchronizationPeriod {
    #[http_enum_case(id="0"; value="i"; description="Immediately Persist")]
    Immediately,
    #[http_enum_case(id="1"; value="1"; description="Persist during 1 sec")]
    Sec1,
    #[http_enum_case(id="5"; value="5";  description="Persist during 5 sec"; default)]
    Sec5,
    #[http_enum_case(id="15"; value="15"; description="Persist during 15 sec")]
    Sec15,
    #[http_enum_case(id="30"; value="30"; description="Persist during 30 sec")]
    Sec30,
    #[http_enum_case(id="60"; value="60"; description="Persist during 1 minute")]
    Min1,
    #[http_enum_case(id="6"; value="a"; description="Sync as soon as CPU schedules task")]
    Asap,
}#[my_http_server_swagger::http_route(
    method: "GET",
    route: "/api/generate/{processId}",
    description: "Generate crypto deposit address",
    controller: "CryptoDeposit",
    result:[
        {status_code: 200, description: "Ok response", model: "CryptoDepositAddressesResponse"},
    ]
)]
#[derive(MyHttpInput)]
pub struct ReadLogsByProcessInputModel {
    #[http_path(name = "processId"; description = "Id of Process")]
    pub process_id: Option<String>,
}
#[derive(MyHttpInput)]
pub struct AuthenticateInputContract {
    #[http_form(description = "Email of user")]
    pub email: String,
    #[http_form(description = "Password of user")]
    pub password: String,
}#[derive(MyHttpInput)]
pub struct AuthenticateInputContract {
    #[http_form(description = "Email of user"; validator="validate_email")]
    pub email: String,
    #[http_form(description = "Password of user")]
    pub password: String,
}
fn validate_email(ctx: &my_http_server::HttpContext, value: &str) -> Result<(), HttpFailResult> {
    Ok(())
}Works with String Types only
#[derive(MyHttpInput)]
pub struct ToLowerCaseFromQuery {
    #[http_query(name = "testToLowerString", to_lowercase, description = "String which is going to be always lowercased")]
    pub test_to_lower_string: String,
    #[http_query(name = "testToLowerStringOpt", to_uppercase, description = "String which is going to be always uppercased")]
    pub test_to_lower_string_opt: Option<String>,
}Uses with serde_json:
#[derive(Serialize, Deserialize, Debug, MyHttpObjectStructure)]
pub struct IsAliveResponse {
    pub name: String,
    pub time: String,
    pub version: String,
    pub env_info: Option<String>,
}It's a common pattern to put some restrictions on input field before it getting inside the system. As an Example - Password usually has to be at leas 8 symbols, Special symbol and other requirements.
#[http_input_field(open_api_type:"Password")]
pub struct PasswordField(String);
fn process_value(src: &str) -> Result<StrOrString, HttpFailResult> {
    //Password Validation
    if src.len() < 8 {
        return Err(HttpFailResult::as_validation_error(
            "Password must be at least 8 characters long".to_string(),
        ));
    }
    let src = src.trim();
    let src = src.to_lowercase();
    Ok(StrOrString::create_as_string(src))
}
let mut cookies = CookieJar::new();
cookies.set_cookie(
  Cookie::new("Test", "Value")
    .set_domain("/")
    .set_max_age(24 * 60 * 60),
);
cookies.set_cookie(("Test2".to_string(), "Value".to_string()));
cookies.set_cookie(("Test3", "Value".to_string()));