Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 2 additions & 53 deletions wp_api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![allow(dead_code, unused_variables)]

use request::{endpoint::ApiEndpoint, WPNetworkRequest, WPNetworkResponse};
use serde::Deserialize;
use request::{endpoint::ApiEndpoint, RequestMethod, WPNetworkRequest, WPNetworkResponse};
use std::collections::HashMap;
use url::Url;

Expand Down Expand Up @@ -356,15 +355,6 @@ impl WPAuthentication {
}
}

#[derive(Debug, uniffi::Enum)]
pub enum RequestMethod {
GET,
POST,
PUT,
DELETE,
HEAD,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum WPApiParamOrder {
#[default]
Expand All @@ -386,43 +376,12 @@ pub fn parse_api_details_response(response: WPNetworkResponse) -> Result<WPAPIDe
let api_details =
serde_json::from_slice(&response.body).map_err(|err| WPApiError::ParsingError {
reason: err.to_string(),
response: String::from_utf8_lossy(&response.body).to_string(),
response: response.body_as_string(),
})?;

Ok(api_details)
}

pub fn parse_wp_response<'de, T: Deserialize<'de>>(
response: &'de WPNetworkResponse,
) -> Result<T, WPApiError> {
parse_response_for_generic_errors(response)?;
serde_json::from_slice(&response.body).map_err(|err| WPApiError::ParsingError {
reason: err.to_string(),
response: String::from_utf8_lossy(&response.body).to_string(),
})
}

pub fn parse_response_for_generic_errors(response: &WPNetworkResponse) -> Result<(), WPApiError> {
let response_str = String::from_utf8_lossy(&response.body).to_string();
// TODO: Further parse the response body to include error message
// TODO: Lots of unwraps to get a basic setup working
let status = http::StatusCode::from_u16(response.status_code).unwrap();
if let Ok(rest_error) = serde_json::from_slice(&response.body) {
Err(WPApiError::RestError {
rest_error,
status_code: response.status_code,
response: response_str,
})
} else if status.is_client_error() || status.is_server_error() {
Err(WPApiError::UnknownError {
status_code: response.status_code,
response: response_str,
})
} else {
Ok(())
}
}

// TODO: Figure out why we can't expose this method on `WPNetworkResponse` via UniFFI
#[uniffi::export]
pub fn get_link_header(response: &WPNetworkResponse, name: &str) -> Option<WPRestAPIURL> {
Expand All @@ -437,16 +396,6 @@ trait SparseField {
fn as_str(&self) -> &str;
}

#[macro_export]
macro_rules! add_uniffi_exported_parser {
($fn_name:ident, $return_type: ty) => {
#[uniffi::export]
pub fn $fn_name(response: &WPNetworkResponse) -> Result<$return_type, WPApiError> {
parse_wp_response(response)
}
};
}

#[macro_export]
macro_rules! generate {
($type_name:ident) => {
Expand Down
4 changes: 1 addition & 3 deletions wp_api/src/plugins.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use serde::{Deserialize, Serialize};
use wp_contextual::WPContextual;

use crate::{
add_uniffi_exported_parser, parse_wp_response, SparseField, WPApiError, WPNetworkResponse,
};
use crate::{add_uniffi_exported_parser, SparseField, WPApiError, WPNetworkResponse};

add_uniffi_exported_parser!(parse_filter_plugins_response, Vec<SparsePlugin>);
add_uniffi_exported_parser!(parse_filter_retrieve_plugin_response, SparsePlugin);
Expand Down
57 changes: 56 additions & 1 deletion wp_api/src/request.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use std::{collections::HashMap, fmt::Debug};

use serde::Deserialize;
use url::Url;

use crate::RequestMethod;
use crate::WPApiError;

pub mod endpoint;

Expand Down Expand Up @@ -80,6 +81,41 @@ impl WPNetworkResponse {
pub fn body_as_string(&self) -> String {
body_as_string(&self.body)
}

pub fn parse<'de, T: Deserialize<'de>>(&'de self) -> Result<T, WPApiError> {
self.parse_response_for_generic_errors()?;
serde_json::from_slice(&self.body).map_err(|err| WPApiError::ParsingError {
reason: err.to_string(),
response: self.body_as_string(),
})
}

pub fn parse_with<F, T>(&self, parser: F) -> Result<T, WPApiError>
where
F: Fn(&WPNetworkResponse) -> Result<T, WPApiError>,
{
parser(self)
}

fn parse_response_for_generic_errors(&self) -> Result<(), WPApiError> {
// TODO: Further parse the response body to include error message
// TODO: Lots of unwraps to get a basic setup working
let status = http::StatusCode::from_u16(self.status_code).unwrap();
if let Ok(rest_error) = serde_json::from_slice(&self.body) {
Err(WPApiError::RestError {
rest_error,
status_code: self.status_code,
response: self.body_as_string(),
})
} else if status.is_client_error() || status.is_server_error() {
Err(WPApiError::UnknownError {
status_code: self.status_code,
response: self.body_as_string(),
})
} else {
Ok(())
}
}
}

impl Debug for WPNetworkResponse {
Expand All @@ -101,6 +137,25 @@ impl Debug for WPNetworkResponse {
}
}

#[derive(Debug, uniffi::Enum)]
pub enum RequestMethod {
GET,
POST,
PUT,
DELETE,
HEAD,
}

fn body_as_string(body: &[u8]) -> String {
String::from_utf8_lossy(body).to_string()
}

#[macro_export]
macro_rules! add_uniffi_exported_parser {
($fn_name:ident, $return_type: ty) => {
#[uniffi::export]
pub fn $fn_name(response: &WPNetworkResponse) -> Result<$return_type, WPApiError> {
response.parse::<$return_type>()
}
};
}
3 changes: 1 addition & 2 deletions wp_api/src/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use serde::{Deserialize, Serialize};
use wp_contextual::WPContextual;

use crate::{
add_uniffi_exported_parser, parse_wp_response, SparseField, WPApiError, WPApiParamOrder,
WPNetworkResponse,
add_uniffi_exported_parser, SparseField, WPApiError, WPApiParamOrder, WPNetworkResponse,
};

add_uniffi_exported_parser!(parse_filter_users_response, Vec<SparseUser>);
Expand Down
29 changes: 7 additions & 22 deletions wp_api/tests/integration_test_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use futures::Future;
use http::HeaderMap;
use std::{fs::read_to_string, process::Command};
use wp_api::{
request::{WPNetworkRequest, WPNetworkResponse},
request::{RequestMethod, WPNetworkRequest, WPNetworkResponse},
users::UserId,
WPApiError, WPApiHelper, WPAuthentication, WPRestError, WPRestErrorCode, WPRestErrorWrapper,
};
Expand Down Expand Up @@ -46,21 +46,6 @@ impl WPNetworkRequestExecutor for WPNetworkRequest {
}
}

pub trait WPNetworkResponseParser {
fn parse<F, T>(&self, parser: F) -> Result<T, WPApiError>
where
F: Fn(&WPNetworkResponse) -> Result<T, WPApiError>;
}

impl WPNetworkResponseParser for WPNetworkResponse {
fn parse<F, T>(&self, parser: F) -> Result<T, WPApiError>
where
F: Fn(&WPNetworkResponse) -> Result<T, WPApiError>,
{
parser(self)
}
}

pub trait AssertWpError<T: std::fmt::Debug> {
fn assert_wp_error(self, expected_error_code: WPRestErrorCode);
}
Expand Down Expand Up @@ -214,13 +199,13 @@ impl AsyncWPNetworking {
})
}

fn request_method(method: wp_api::RequestMethod) -> http::Method {
fn request_method(method: RequestMethod) -> http::Method {
match method {
wp_api::RequestMethod::GET => reqwest::Method::GET,
wp_api::RequestMethod::POST => reqwest::Method::POST,
wp_api::RequestMethod::PUT => reqwest::Method::PUT,
wp_api::RequestMethod::DELETE => reqwest::Method::DELETE,
wp_api::RequestMethod::HEAD => reqwest::Method::HEAD,
RequestMethod::GET => reqwest::Method::GET,
RequestMethod::POST => reqwest::Method::POST,
RequestMethod::PUT => reqwest::Method::PUT,
RequestMethod::DELETE => reqwest::Method::DELETE,
RequestMethod::HEAD => reqwest::Method::HEAD,
}
}
}
16 changes: 8 additions & 8 deletions wp_api/tests/test_plugins_err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use wp_api::plugins::{PluginCreateParams, PluginStatus, PluginUpdateParams};
use wp_api::{WPContext, WPRestErrorCode};

use crate::integration_test_common::{
api, api_as_subscriber, AssertWpError, WPNetworkRequestExecutor, WPNetworkResponseParser,
HELLO_DOLLY_PLUGIN_SLUG, WP_ORG_PLUGIN_SLUG_CLASSIC_WIDGETS,
api, api_as_subscriber, AssertWpError, WPNetworkRequestExecutor, HELLO_DOLLY_PLUGIN_SLUG,
WP_ORG_PLUGIN_SLUG_CLASSIC_WIDGETS,
};

pub mod integration_test_common;
Expand All @@ -18,7 +18,7 @@ async fn create_plugin_err_cannot_install_plugin() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_create_plugin_response)
.parse_with(wp_api::plugins::parse_create_plugin_response)
.assert_wp_error(WPRestErrorCode::CannotInstallPlugin);
}

Expand All @@ -29,7 +29,7 @@ async fn delete_plugin_err_cannot_delete_active_plugin() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_delete_plugin_response)
.parse_with(wp_api::plugins::parse_delete_plugin_response)
.assert_wp_error(WPRestErrorCode::CannotDeleteActivePlugin);
}

Expand All @@ -40,7 +40,7 @@ async fn list_plugins_err_cannot_view_plugins() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_retrieve_plugin_response_with_edit_context)
.parse_with(wp_api::plugins::parse_retrieve_plugin_response_with_edit_context)
.assert_wp_error(WPRestErrorCode::CannotViewPlugins);
}

Expand All @@ -51,7 +51,7 @@ async fn retrieve_plugin_err_cannot_view_plugin() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_retrieve_plugin_response_with_edit_context)
.parse_with(wp_api::plugins::parse_retrieve_plugin_response_with_edit_context)
.assert_wp_error(WPRestErrorCode::CannotViewPlugin);
}

Expand All @@ -67,7 +67,7 @@ async fn update_plugin_err_plugin_not_found() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_update_plugin_response)
.parse_with(wp_api::plugins::parse_update_plugin_response)
.assert_wp_error(WPRestErrorCode::PluginNotFound);
}

Expand All @@ -83,6 +83,6 @@ async fn update_plugin_err_cannot_manage_plugins() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_update_plugin_response)
.parse_with(wp_api::plugins::parse_update_plugin_response)
.assert_wp_error(WPRestErrorCode::CannotManagePlugins);
}
9 changes: 4 additions & 5 deletions wp_api/tests/test_plugins_immut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ use wp_api::{
};

use crate::integration_test_common::{
api, WPNetworkRequestExecutor, WPNetworkResponseParser, CLASSIC_EDITOR_PLUGIN_SLUG,
HELLO_DOLLY_PLUGIN_SLUG,
api, WPNetworkRequestExecutor, CLASSIC_EDITOR_PLUGIN_SLUG, HELLO_DOLLY_PLUGIN_SLUG,
};

pub mod integration_test_common;
Expand All @@ -29,7 +28,7 @@ async fn filter_plugins(
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_filter_plugins_response);
.parse_with(wp_api::plugins::parse_filter_plugins_response);
assert!(parsed_response.is_ok());
parsed_response
.unwrap()
Expand All @@ -48,7 +47,7 @@ async fn filter_retrieve_plugin(
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_filter_retrieve_plugin_response);
.parse_with(wp_api::plugins::parse_filter_retrieve_plugin_response);
assert!(plugin_result.is_ok());
validate_sparse_plugin_fields(&plugin_result.unwrap(), fields);
}
Expand Down Expand Up @@ -115,7 +114,7 @@ async fn retrieve_plugin_with_edit_context(
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_retrieve_plugin_response_with_edit_context);
.parse_with(wp_api::plugins::parse_retrieve_plugin_response_with_edit_context);
assert!(
parsed_response.is_ok(),
"Retrieve plugin failed!\nContext: {:?}\nPlugin: {:?}\nResponse was: '{:?}'",
Expand Down
10 changes: 5 additions & 5 deletions wp_api/tests/test_plugins_mut.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use wp_api::plugins::{PluginCreateParams, PluginStatus, PluginUpdateParams};

use crate::integration_test_common::{
api, run_and_restore_wp_content_plugins, WPNetworkRequestExecutor, WPNetworkResponseParser,
CLASSIC_EDITOR_PLUGIN_SLUG, HELLO_DOLLY_PLUGIN_SLUG, WP_ORG_PLUGIN_SLUG_CLASSIC_WIDGETS,
api, run_and_restore_wp_content_plugins, WPNetworkRequestExecutor, CLASSIC_EDITOR_PLUGIN_SLUG,
HELLO_DOLLY_PLUGIN_SLUG, WP_ORG_PLUGIN_SLUG_CLASSIC_WIDGETS,
};

pub mod integration_test_common;
Expand All @@ -22,7 +22,7 @@ async fn create_plugin() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_create_plugin_response)
.parse_with(wp_api::plugins::parse_create_plugin_response)
.unwrap();
println!("Created Plugin: {:?}", created_plugin);
})
Expand All @@ -43,7 +43,7 @@ async fn update_plugin() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_update_plugin_response)
.parse_with(wp_api::plugins::parse_update_plugin_response)
.unwrap();
println!("Updated Plugin: {:?}", updated_plugin);
})
Expand All @@ -60,7 +60,7 @@ async fn delete_plugin() {
.execute()
.await
.unwrap()
.parse(wp_api::plugins::parse_delete_plugin_response)
.parse_with(wp_api::plugins::parse_delete_plugin_response)
.unwrap();
println!("Deleted Plugin: {:?}", deleted_plugin);
})
Expand Down
Loading