Skip to content

Commit

Permalink
fix: cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
qinluhe committed Mar 29, 2024
1 parent 99287b0 commit eb1aa08
Show file tree
Hide file tree
Showing 5 changed files with 1,381 additions and 1,372 deletions.
102 changes: 51 additions & 51 deletions libs/client-api-for-wasm/src/entities.rs
Original file line number Diff line number Diff line change
@@ -1,79 +1,79 @@
use client_api::error::ErrorCode;
use serde::{Deserialize, Serialize};
use tsify::Tsify;
use wasm_bindgen::JsValue;
use client_api::error::{ErrorCode};

#[derive(Tsify, Serialize, Deserialize, Default, Debug)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct Configuration {
pub compression_quality: u32,
pub compression_buffer_size: usize,
pub compression_quality: u32,
pub compression_buffer_size: usize,
}

#[derive(Tsify, Serialize, Deserialize, Default, Debug)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct ClientAPIConfig {
pub base_url: String,
pub ws_addr: String,
pub gotrue_url: String,
pub device_id: String,
pub configuration: Configuration,
pub client_id: String,
pub base_url: String,
pub ws_addr: String,
pub gotrue_url: String,
pub device_id: String,
pub configuration: Configuration,
pub client_id: String,
}

#[derive(Tsify, Serialize, Deserialize, Default, Debug)]
#[repr(i32)]
pub enum ClientErrorCode {
#[default]
Ok = 0,
Unhandled = -1,
RecordNotFound = -2,
RecordAlreadyExists = -3,
InvalidEmail = 1001,
InvalidPassword = 1002,
OAuthError = 1003,
MissingPayload = 1004,
DBError = 1005,
OpenError = 1006,
InvalidUrl = 1007,
InvalidRequest = 1008,
InvalidOAuthProvider = 1009,
NotLoggedIn = 1011,
NotEnoughPermissions = 1012,
#[default]
Ok = 0,
Unhandled = -1,
RecordNotFound = -2,
RecordAlreadyExists = -3,
InvalidEmail = 1001,
InvalidPassword = 1002,
OAuthError = 1003,
MissingPayload = 1004,
DBError = 1005,
OpenError = 1006,
InvalidUrl = 1007,
InvalidRequest = 1008,
InvalidOAuthProvider = 1009,
NotLoggedIn = 1011,
NotEnoughPermissions = 1012,
}

impl From<ErrorCode> for ClientErrorCode {
fn from(value: ErrorCode) -> Self {
match value {
ErrorCode::Ok => Self::Ok,
ErrorCode::Unhandled => Self::Unhandled,
ErrorCode::RecordNotFound => Self::RecordNotFound,
ErrorCode::RecordAlreadyExists => Self::RecordAlreadyExists,
ErrorCode::InvalidEmail => Self::InvalidEmail,
ErrorCode::InvalidPassword => Self::InvalidPassword,
ErrorCode::OAuthError => Self::OAuthError,
ErrorCode::MissingPayload => Self::MissingPayload,
ErrorCode::DBError => Self::DBError,
ErrorCode::OpenError => Self::OpenError,
ErrorCode::InvalidUrl => Self::InvalidUrl,
ErrorCode::InvalidRequest => Self::InvalidRequest,
ErrorCode::InvalidOAuthProvider => Self::InvalidOAuthProvider,
ErrorCode::NotLoggedIn => Self::NotLoggedIn,
ErrorCode::NotEnoughPermissions => Self::NotEnoughPermissions,
_ => Self::Unhandled,
}
}
fn from(value: ErrorCode) -> Self {
match value {
ErrorCode::Ok => Self::Ok,
ErrorCode::Unhandled => Self::Unhandled,
ErrorCode::RecordNotFound => Self::RecordNotFound,
ErrorCode::RecordAlreadyExists => Self::RecordAlreadyExists,
ErrorCode::InvalidEmail => Self::InvalidEmail,
ErrorCode::InvalidPassword => Self::InvalidPassword,
ErrorCode::OAuthError => Self::OAuthError,
ErrorCode::MissingPayload => Self::MissingPayload,
ErrorCode::DBError => Self::DBError,
ErrorCode::OpenError => Self::OpenError,
ErrorCode::InvalidUrl => Self::InvalidUrl,
ErrorCode::InvalidRequest => Self::InvalidRequest,
ErrorCode::InvalidOAuthProvider => Self::InvalidOAuthProvider,
ErrorCode::NotLoggedIn => Self::NotLoggedIn,
ErrorCode::NotEnoughPermissions => Self::NotEnoughPermissions,
_ => Self::Unhandled,
}
}
}

#[derive(Tsify, Serialize, Deserialize, Default, Debug)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct ClientResponse {
pub code: ClientErrorCode,
pub message: String,
pub code: ClientErrorCode,
pub message: String,
}

impl From<ClientResponse> for JsValue {
fn from(value: ClientResponse) -> Self {
JsValue::from_str(&serde_json::to_string(&value).unwrap())
}
}
fn from(value: ClientResponse) -> Self {
JsValue::from_str(&serde_json::to_string(&value).unwrap())
}
}
108 changes: 59 additions & 49 deletions libs/client-api-for-wasm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
mod logger;
mod entities;
mod logger;

use wasm_bindgen::prelude::*;
use client_api::{Client, ClientConfiguration};
use crate::entities::{ClientAPIConfig, ClientErrorCode, ClientResponse};
use crate::logger::{init_logger};
use crate::logger::init_logger;
use client_api::{Client, ClientConfiguration};
use wasm_bindgen::prelude::*;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
Expand All @@ -14,60 +14,70 @@ static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = window)]
fn wasm_trace(level: &str, target: &str, msg: &str);
#[wasm_bindgen(js_namespace = window)]
fn wasm_trace(level: &str, target: &str, msg: &str);
}

#[wasm_bindgen]
pub struct ClientAPI {
client: Client,
client: Client,
}

#[wasm_bindgen]
impl ClientAPI {
pub fn new(config: ClientAPIConfig) -> ClientAPI {
init_logger();
let configuration = ClientConfiguration::default();
configuration.to_owned().with_compression_buffer_size(config.configuration.compression_buffer_size);
configuration.to_owned().with_compression_quality(config.configuration.compression_quality);

let client = Client::new(config.base_url.as_str(), config.ws_addr.as_str(), config.gotrue_url.as_str(), config.device_id.as_str(), configuration, config.client_id.as_str());
log::debug!("Client API initialized, config: {:?}", config);
ClientAPI {
client,
}
}

// pub async fn get_user(&self) -> ClientResponse {
// if let Err(err) = self.client.get_profile().await {
// log::error!("Get user failed: {:?}", err);
// return ClientResponse<bool> {
// code: ClientErrorCode::from(err.code),
// message: err.message.to_string(),
// data: None
// }
// }
//
// log::info!("Get user success");
// ClientResponse {
// code: ClientErrorCode::Ok,
// message: "Get user success".to_string(),
// }
// }
pub fn new(config: ClientAPIConfig) -> ClientAPI {
init_logger();
let configuration = ClientConfiguration::default();
configuration
.to_owned()
.with_compression_buffer_size(config.configuration.compression_buffer_size);
configuration
.to_owned()
.with_compression_quality(config.configuration.compression_quality);

pub async fn sign_in_password(&self, email: &str, password: &str) -> Result<bool, ClientResponse>
{
if let Err(err) = self.client.sign_in_password(email, password).await {
log::error!("Sign in failed: {:?}", err);
return Err(ClientResponse {
code: ClientErrorCode::from(err.code),
message: err.message.to_string(),
})
}
let client = Client::new(
config.base_url.as_str(),
config.ws_addr.as_str(),
config.gotrue_url.as_str(),
config.device_id.as_str(),
configuration,
config.client_id.as_str(),
);
log::debug!("Client API initialized, config: {:?}", config);
ClientAPI { client }
}

log::info!("Sign in success");
Ok(true)
}
}
// pub async fn get_user(&self) -> ClientResponse {
// if let Err(err) = self.client.get_profile().await {
// log::error!("Get user failed: {:?}", err);
// return ClientResponse<bool> {
// code: ClientErrorCode::from(err.code),
// message: err.message.to_string(),
// data: None
// }
// }
//
// log::info!("Get user success");
// ClientResponse {
// code: ClientErrorCode::Ok,
// message: "Get user success".to_string(),
// }
// }

pub async fn sign_in_password(
&self,
email: &str,
password: &str,
) -> Result<bool, ClientResponse> {
if let Err(err) = self.client.sign_in_password(email, password).await {
log::error!("Sign in failed: {:?}", err);
return Err(ClientResponse {
code: ClientErrorCode::from(err.code),
message: err.message.to_string(),
});
}

log::info!("Sign in success");
Ok(true)
}
}
41 changes: 20 additions & 21 deletions libs/client-api-for-wasm/src/logger.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,37 @@
use crate::wasm_trace;

pub fn set_panic_hook() {
#[cfg(debug_assertions)]
console_error_panic_hook::set_once();
#[cfg(debug_assertions)]
console_error_panic_hook::set_once();
}


pub struct WASMLogger;

impl log::Log for WASMLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= log::Level::Debug
}

fn log(&self, record: &log::Record) {
let level = record.level();
let target = record.target();
let args = format!("{}", record.args());
wasm_trace(&level.to_string(), target, &args);
}

fn flush(&self) {}
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= log::Level::Debug
}

fn log(&self, record: &log::Record) {
let level = record.level();
let target = record.target();
let args = format!("{}", record.args());
wasm_trace(&level.to_string(), target, &args);
}

fn flush(&self) {}
}

impl Default for WASMLogger {
fn default() -> Self {
Self
}
fn default() -> Self {
Self
}
}

static WASM_LOGGER: WASMLogger = WASMLogger;

pub fn init_logger() {
set_panic_hook();
log::set_logger(&WASM_LOGGER).unwrap();
log::set_max_level(log::LevelFilter::Debug);
set_panic_hook();
log::set_logger(&WASM_LOGGER).unwrap();
log::set_max_level(log::LevelFilter::Debug);
}
2 changes: 1 addition & 1 deletion libs/client-api-for-wasm/tests/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ wasm_bindgen_test_configure!(run_in_browser);

#[wasm_bindgen_test]
fn pass() {
assert_eq!(1 + 1, 2);
assert_eq!(1 + 1, 2);
}
Loading

0 comments on commit eb1aa08

Please sign in to comment.