trello-to-deck/src/trello/client.rs

107 lines
3.2 KiB
Rust
Raw Normal View History

//
use std::collections::HashMap;
use kxio::net::{Net, ReqBuilder};
use crate::trello::model::{TrelloAttachment, TrelloAttachmentId};
use crate::{
api_result::APIResult,
f, s,
trello::model::{
board::TrelloBoard,
card::{TrelloLongCard, TrelloShortCard},
TrelloBoardId, TrelloCardId, TrelloListId,
},
FullCtx,
};
pub(crate) struct TrelloClient<'ctx> {
ctx: &'ctx FullCtx,
}
impl<'ctx> TrelloClient<'ctx> {
fn url(&self, path: impl Into<String>) -> String {
let path = path.into();
assert!(path.starts_with("/"));
f!("https://api.trello.com/1{path}")
}
fn common_headers(&self) -> HashMap<String, String> {
let api_key = &self.ctx.cfg.trello.api_key;
let api_secret = &self.ctx.cfg.trello.api_secret;
HashMap::from([
(s!("accept"), s!("application/json")),
(s!("content-type"), s!("application/json")),
(
s!("Authorization"),
f!(r#"OAuth oauth_consumer_key="{api_key}", oauth_token="{api_secret}""#,),
),
])
}
async fn request<T: for<'a> serde::Deserialize<'a>>(
&self,
url: impl Into<String>,
custom: fn(&Net, String) -> ReqBuilder,
) -> APIResult<T> {
APIResult::new(
custom(&self.ctx.net, self.url(url))
.headers(self.common_headers())
.send()
.await,
&self.ctx.prt,
)
.await
}
}
impl<'ctx> TrelloClient<'ctx> {
// https://developer.atlassian.com/cloud/trello/rest/api-group-members/#api-members-id-boards-get
pub(crate) async fn boards(&self) -> APIResult<Vec<TrelloBoard>> {
self.request("/members/me/boards?lists=open", |net, url| net.get(url))
.await
}
// https://developer.atlassian.com/cloud/trello/rest/api-group-boards/#api-boards-id-get
pub(crate) async fn board(&self, board_id: &TrelloBoardId) -> APIResult<TrelloBoard> {
self.request(f!("/boards/{board_id}?lists=open"), |net, url| net.get(url))
.await
}
// https://developer.atlassian.com/cloud/trello/rest/api-group-lists/#api-lists-id-cards-get
pub(crate) async fn list_cards(
&self,
list_id: &TrelloListId,
) -> APIResult<Vec<TrelloShortCard>> {
self.request(f!("/lists/{list_id}/cards"), |net, url| net.get(url))
.await
}
// https://developer.atlassian.com/cloud/trello/rest/api-group-cards/#api-cards-id-get
pub(crate) async fn card(&self, card_id: &TrelloCardId) -> APIResult<TrelloLongCard> {
self.request(f!("/cards/{card_id}?attachments=true"), |net, url| {
net.get(url)
})
.await
}
// https://developer.atlassian.com/cloud/trello/rest/api-group-cards/#api-cards-id-attachments-idattachment-get
pub(crate) async fn card_attachment(
&self,
card_id: &TrelloCardId,
attachment_id: &TrelloAttachmentId,
) -> APIResult<TrelloAttachment> {
self.request(
f!("/cards/{card_id}/attachments/{attachment_id}"),
|net, url| net.get(url),
)
.await
}
}
impl TrelloClient<'_> {
pub(crate) fn new(ctx: &FullCtx) -> TrelloClient {
TrelloClient { ctx }
}
}