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
use reqwest::Client; use reqwest::Error as ReqwestError; use serde::{Deserialize, Serialize}; #[derive(Debug)] pub enum CreateFileError { SendFailed(ReqwestError), ReceiveFailed(ReqwestError), InvalidAuth, ExpiredAuth, FileIdTaken, FilePathTaken, Unspecified, } #[derive(Debug)] pub struct CreateFileRequest { pub username: String, pub auth: String, pub file_id: String, pub file_name: String, pub file_path: String, pub file_content: String, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct CreateFileResponse { pub error_code: String, pub current_version: u64, } pub fn create_file( api_location: String, params: &CreateFileRequest, ) -> Result<u64, CreateFileError> { let client = Client::new(); let form_params = [ ("username", params.username.as_str()), ("auth", params.auth.as_str()), ("file_id", params.file_id.as_str()), ("file_name", params.file_name.as_str()), ("file_path", params.file_path.as_str()), ("file_content", params.file_content.as_str()), ]; let mut response = client .post(format!("{}/create-file", api_location).as_str()) .form(&form_params) .send() .map_err(|err| CreateFileError::SendFailed(err))?; let response_body = response .json::<CreateFileResponse>() .map_err(|err| CreateFileError::ReceiveFailed(err))?; match ( response.status().as_u16(), response_body.error_code.as_str(), ) { (200..=299, _) => Ok(response_body.current_version), (401, "invalid_auth") => Err(CreateFileError::InvalidAuth), (401, "expired_auth") => Err(CreateFileError::ExpiredAuth), (422, "file_id_taken") => Err(CreateFileError::FileIdTaken), (422, "file_path_taken") => Err(CreateFileError::FilePathTaken), _ => Err(CreateFileError::Unspecified), } }