1
0
Fork 0
mirror of https://github.com/Nutomic/ibis.git synced 2024-11-26 06:31:09 +00:00
ibis/src/frontend/api.rs

189 lines
6.1 KiB
Rust
Raw Normal View History

2024-01-18 11:38:31 +00:00
use crate::common::ResolveObject;
use crate::common::{ApiConflict, ListArticlesData};
2024-01-16 15:07:01 +00:00
use crate::common::{ArticleView, LoginUserData, RegisterUserData};
2024-01-18 11:38:31 +00:00
use crate::common::{CreateArticleData, EditArticleData, ForkArticleData, LocalUserView};
2024-01-17 16:14:16 +00:00
use crate::common::{DbArticle, GetArticleData};
2024-01-18 11:38:31 +00:00
use crate::common::{DbInstance, FollowInstance, InstanceView, SearchArticleData};
use crate::frontend::error::MyResult;
2024-01-03 16:06:52 +00:00
use anyhow::anyhow;
2024-01-17 16:14:16 +00:00
use reqwest::{Client, RequestBuilder, StatusCode};
2024-01-03 16:06:52 +00:00
use serde::{Deserialize, Serialize};
2024-01-17 16:14:16 +00:00
use url::Url;
2024-01-03 16:06:52 +00:00
2024-01-17 15:40:01 +00:00
#[derive(Clone)]
pub struct ApiClient {
2024-01-18 11:18:17 +00:00
client: Client,
2024-01-17 15:40:01 +00:00
pub hostname: String,
}
impl ApiClient {
pub fn new(client: Client, hostname: String) -> Self {
Self { client, hostname }
}
async fn get_query<T, R>(&self, endpoint: &str, query: Option<R>) -> MyResult<T>
where
T: for<'de> Deserialize<'de>,
R: Serialize,
{
let mut req = self
.client
.get(format!("http://{}/api/v1/{}", &self.hostname, endpoint));
if let Some(query) = query {
req = req.query(&query);
}
handle_json_res::<T>(req).await
}
pub async fn get_article(&self, data: GetArticleData) -> MyResult<ArticleView> {
self.get_query("article", Some(data)).await
}
pub async fn list_articles(&self, data: ListArticlesData) -> MyResult<Vec<DbArticle>> {
self.get_query("article/list", Some(data)).await
2024-01-17 15:40:01 +00:00
}
pub async fn register(&self, register_form: RegisterUserData) -> MyResult<LocalUserView> {
let req = self
.client
.post(format!("http://{}/api/v1/account/register", self.hostname))
.form(&register_form);
handle_json_res::<LocalUserView>(req).await
}
pub async fn login(&self, login_form: LoginUserData) -> MyResult<LocalUserView> {
let req = self
.client
.post(format!("http://{}/api/v1/account/login", self.hostname))
.form(&login_form);
handle_json_res::<LocalUserView>(req).await
}
2024-01-17 16:14:16 +00:00
2024-01-30 15:06:02 +00:00
pub async fn create_article(&self, data: &CreateArticleData) -> MyResult<ArticleView> {
2024-01-17 16:14:16 +00:00
let req = self
.client
.post(format!("http://{}/api/v1/article", &self.hostname))
2024-01-30 15:06:02 +00:00
.form(data);
handle_json_res(req).await
2024-01-17 16:14:16 +00:00
}
pub async fn edit_article_with_conflict(
&self,
edit_form: &EditArticleData,
) -> MyResult<Option<ApiConflict>> {
let req = self
.client
.patch(format!("http://{}/api/v1/article", self.hostname))
.form(edit_form);
handle_json_res(req).await
}
pub async fn edit_article(&self, edit_form: &EditArticleData) -> MyResult<ArticleView> {
let edit_res = self.edit_article_with_conflict(edit_form).await?;
assert!(edit_res.is_none());
self.get_article(GetArticleData {
title: None,
2024-02-09 13:46:33 +00:00
instance_domain: None,
2024-01-17 16:14:16 +00:00
id: Some(edit_form.article_id),
})
.await
}
pub async fn search(&self, search_form: &SearchArticleData) -> MyResult<Vec<DbArticle>> {
self.get_query("search", Some(search_form)).await
}
pub async fn get_local_instance(&self) -> MyResult<InstanceView> {
self.get_query("instance", None::<i32>).await
}
pub async fn follow_instance(&self, follow_instance: &str) -> MyResult<DbInstance> {
// fetch beta instance on alpha
let resolve_form = ResolveObject {
id: Url::parse(&format!("http://{}", follow_instance))?,
};
2024-01-18 14:31:32 +00:00
let instance_resolved: DbInstance = self
.get_query("instance/resolve", Some(resolve_form))
.await?;
2024-01-17 16:14:16 +00:00
// send follow
let follow_form = FollowInstance {
id: instance_resolved.id,
};
// cant use post helper because follow doesnt return json
let res = self
.client
.post(format!("http://{}/api/v1/instance/follow", self.hostname))
.form(&follow_form)
.send()
.await?;
if res.status() == StatusCode::OK {
Ok(instance_resolved)
} else {
Err(anyhow!("API error: {}", res.text().await?).into())
}
}
2024-01-18 11:18:17 +00:00
pub async fn my_profile(&self) -> MyResult<LocalUserView> {
let req = self.client.get(format!(
"http://{}/api/v1/account/my_profile",
self.hostname
));
handle_json_res::<LocalUserView>(req).await
}
pub async fn logout(&self) -> MyResult<()> {
self.client
.get(format!("http://{}/api/v1/account/logout", self.hostname))
.send()
.await?;
Ok(())
}
pub async fn fork_article(&self, form: &ForkArticleData) -> MyResult<ArticleView> {
let req = self
.client
.post(format!("http://{}/api/v1/article/fork", self.hostname))
.form(form);
Ok(handle_json_res(req).await.unwrap())
}
pub async fn get_conflicts(&self) -> MyResult<Vec<ApiConflict>> {
let req = self
.client
.get(format!("http://{}/api/v1/edit_conflicts", &self.hostname));
Ok(handle_json_res(req).await.unwrap())
}
2024-02-01 15:51:38 +00:00
pub async fn resolve_article(&self, id: Url) -> MyResult<ArticleView> {
2024-01-18 11:18:17 +00:00
let resolve_object = ResolveObject { id };
2024-01-18 14:31:32 +00:00
self.get_query("article/resolve", Some(resolve_object))
.await
2024-01-18 11:18:17 +00:00
}
pub async fn resolve_instance(&self, id: Url) -> MyResult<DbInstance> {
let resolve_object = ResolveObject { id };
2024-01-18 14:31:32 +00:00
self.get_query("instance/resolve", Some(resolve_object))
.await
2024-01-18 11:18:17 +00:00
}
2024-01-03 16:06:52 +00:00
}
2024-01-18 14:31:32 +00:00
async fn handle_json_res<T>(#[allow(unused_mut)] mut req: RequestBuilder) -> MyResult<T>
2024-01-03 16:06:52 +00:00
where
T: for<'de> Deserialize<'de>,
{
2024-01-18 14:31:32 +00:00
#[cfg(not(feature = "ssr"))]
{
req = req.fetch_credentials_include();
2024-01-03 16:06:52 +00:00
}
2024-01-11 15:50:57 +00:00
let res = req.send().await?;
2024-01-03 16:06:52 +00:00
let status = res.status();
2024-01-11 15:50:57 +00:00
let text = res.text().await?;
2024-01-18 14:31:32 +00:00
if status == StatusCode::OK {
Ok(serde_json::from_str(&text).map_err(|e| anyhow!("Json error on {text}: {e}"))?)
2024-01-03 16:06:52 +00:00
} else {
2024-01-11 15:50:57 +00:00
Err(anyhow!("API error: {text}").into())
2024-01-03 16:06:52 +00:00
}
}