Skip to content

Commit

Permalink
feat(post option)!: rename search to search-self
Browse files Browse the repository at this point in the history
  • Loading branch information
Thaumy committed Sep 28, 2023
1 parent 7d0ab85 commit 54ef43a
Show file tree
Hide file tree
Showing 9 changed files with 119 additions and 25 deletions.
2 changes: 1 addition & 1 deletion src/api/post/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub mod get_count;
pub mod get_meta_list;
pub mod get_one;
pub mod get_one_raw;
pub mod search;
pub mod search_self;
pub mod update;

pub struct Post {
Expand Down
94 changes: 94 additions & 0 deletions src/api/post/search_self.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use crate::api::post::Post;
use crate::blog_backend;
use crate::infra::http::{body_or_err, RequestBuilderExt};
use crate::infra::iter::IntoIteratorExt;
use crate::infra::json;
use crate::infra::result::WrapResult;
use anyhow::Result;
use serde_json::Value;
use std::collections::HashSet;
use std::iter;

impl Post {
pub async fn search_self(
&self,
skip: usize,
take: usize,
keyword: &str,
) -> Result<(Vec<usize>, usize)> {
let client = &reqwest::Client::new();

// total_count is used for patch the buggy blog backend API
// If index is greater than the max page index, API will still return the last page
let total_count = {
let req = {
let url = blog_backend!("/posts/list");
let query = [
("t", 1.to_string()),
("p", 1.to_string()),
("s", 1.to_string()),
("search", keyword.to_string()),
];
client.get(url).query(&query).pat_auth(&self.pat)
};
let resp = req.send().await?;

// total_count
{
let body = body_or_err(resp).await?;
let json = json::deserialize::<Value>(&body)?;
json["postsCount"]
.as_u64()
.expect("as_u64 failed for `postsCount`") as usize
}
};

let range = (skip + 1)..=(skip + take).min(total_count);
let id_list = range
.map(|i| async move {
let req = {
let url = blog_backend!("/posts/list");
let query = [
("t", 1.to_string()),
("p", i.to_string()),
("s", 1.to_string()),
("search", keyword.to_string()),
];
client.get(url).query(&query).pat_auth(&self.pat)
};
let resp = req.send().await?;

let id_list = {
let body = body_or_err(resp).await?;
let mut json = json::deserialize::<Value>(&body)?;
let post_id = {
let json = json["postList"].take();
let [post, ..] = serde_json::from_value::<[Value; 1]>(json)?;
post["id"].as_u64().expect("as_u64 failed for `id`") as usize
};
let zzk_post_id_list = {
let json = json["zzkSearchResult"]["postIds"].take();
serde_json::from_value::<Vec<usize>>(json)
}?;

zzk_post_id_list
.into_iter()
.chain(iter::once(post_id))
.collect::<Vec<usize>>()
};

id_list.wrap_ok::<anyhow::Error>()
})
.join_all()
.await
.into_iter()
.collect::<Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect::<HashSet<_>>()
.into_iter()
.collect::<Vec<_>>();

(id_list, total_count).wrap_ok()
}
}
10 changes: 5 additions & 5 deletions src/args/cmd/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ pub struct Opt {
pub delete: bool,

#[arg(verbatim_doc_comment)]
/// Search post by keyword and output the post id list that matches
/// Example: cnb post --search 'Hello world'
/// Search self post by keyword and output the post id list that matches
/// Example: cnb post --search-self 'Hello world'
/// *
#[arg(long)]
#[arg(short = 'f')]
#[arg(visible_alias = "find")]
#[arg(visible_alias = "f-self")]
#[arg(visible_alias = "find-self")]
#[arg(value_name = "KEYWORD")]
pub search: Option<String>,
pub search_self: Option<String>,

#[command(subcommand)]
pub cmd: Option<Cmd>,
Expand Down
18 changes: 9 additions & 9 deletions src/args/parser/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub fn list_post(args: &Args) -> Option<(usize, usize)> {
show_comment: false,
list: true,
delete: false,
search: None,
search_self: None,
cmd: None,
})),
id: None,
Expand Down Expand Up @@ -41,7 +41,7 @@ pub fn show_post(args: &Args) -> Option<usize> {
show_comment: false,
list: false,
delete: false,
search: None,
search_self: None,
cmd: None,
})),
id: Some(id),
Expand All @@ -65,7 +65,7 @@ pub fn show_post_meta(args: &Args) -> Option<usize> {
show_comment: false,
list: false,
delete: false,
search: None,
search_self: None,
cmd: None,
})),
id: Some(id),
Expand All @@ -89,7 +89,7 @@ pub fn show_post_comment(args: &Args) -> Option<usize> {
show_comment: true,
list: false,
delete: false,
search: None,
search_self: None,
cmd: None,
})),
id: Some(id),
Expand All @@ -103,7 +103,7 @@ pub fn show_post_comment(args: &Args) -> Option<usize> {
.wrap_some()
}

pub fn search_post(args: &Args) -> Option<(&String, usize, usize)> {
pub fn search_self_post(args: &Args) -> Option<(&String, usize, usize)> {
match args {
Args {
cmd:
Expand All @@ -113,7 +113,7 @@ pub fn search_post(args: &Args) -> Option<(&String, usize, usize)> {
show_comment: false,
list: false,
delete: false,
search: Some(keyword),
search_self: Some(keyword),
cmd: None,
})),
id: None,
Expand Down Expand Up @@ -141,7 +141,7 @@ pub fn delete_post(args: &Args) -> Option<usize> {
show_comment: false,
list: false,
delete: true,
search: None,
search_self: None,
cmd: None,
})),
id: Some(id),
Expand All @@ -165,7 +165,7 @@ pub fn create_post(args: &Args) -> Option<&CreateCmd> {
show_comment: false,
list: false,
delete: false,
search: None,
search_self: None,
cmd: Some(cmd::post::Cmd::Create(cmd)),
})),
id: None,
Expand All @@ -189,7 +189,7 @@ pub fn update_post(args: &Args) -> Option<(usize, &UpdateCmd)> {
show_comment: false,
list: false,
delete: false,
search: None,
search_self: None,
cmd: Some(cmd::post::Cmd::Update(cmd)),
})),
id: Some(id),
Expand Down
2 changes: 1 addition & 1 deletion src/display/colorful/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ pub fn show_post_comment(
})
}

pub fn search_post(
pub fn search_self_post(
result: Result<(impl ExactSizeIterator<Item = usize>, usize)>,
) -> Result<String> {
let (mut id_iter, total_count) = match result {
Expand Down
2 changes: 1 addition & 1 deletion src/display/json/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub fn show_post_comment(
fmt_ok(comment_vec)
}

pub fn search_post(result: Result<(impl ExactSizeIterator<Item = usize>, usize)>) -> String {
pub fn search_self_post(result: Result<(impl ExactSizeIterator<Item = usize>, usize)>) -> String {
let (id_iter, total_count) = match result {
Ok(o) => o,
Err(e) => return fmt_err(&e),
Expand Down
8 changes: 4 additions & 4 deletions src/display/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,14 @@ pub fn delete_post(style: &Style, result: &Result<usize>) -> String {
}
}

pub fn search_post(
pub fn search_self_post(
style: &Style,
result: Result<(impl ExactSizeIterator<Item = usize>, usize)>,
) -> Result<String> {
match style {
Style::Colorful => colorful::post::search_post(result),
Style::Normal => normal::post::search_post(result),
Style::Json => json::post::search_post(result).wrap_ok(),
Style::Colorful => colorful::post::search_self_post(result),
Style::Normal => normal::post::search_self_post(result),
Style::Json => json::post::search_self_post(result).wrap_ok(),
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/display/normal/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ pub fn show_post_comment(
})
}

pub fn search_post(
pub fn search_self_post(
result: Result<(impl ExactSizeIterator<Item = usize>, usize)>,
) -> Result<String> {
let (mut id_iter, total_count) = match result {
Expand Down
6 changes: 3 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,13 @@ async fn main() -> Result<()> {
foe.then(|| panic_if_err(&id));
display::delete_post(style, &id)
}
_ if let Some((kw, skip, take)) = parser::post::search_post(&args) => {
_ if let Some((kw, skip, take)) = parser::post::search_self_post(&args) => {
let result = Post::new(pat?)
.search(skip, take, kw)
.search_self(skip, take, kw)
.await
.map(|(vec, count)| (vec.into_iter().dyn_rev(rev), count));
foe.then(|| panic_if_err(&result));
display::search_post(style, result)?
display::search_self_post(style, result)?
}
_ if let Some(create_cmd) = parser::post::create_post(&args) => {
let CreateCmd { title, body, publish } = create_cmd;
Expand Down

0 comments on commit 54ef43a

Please sign in to comment.