Skip to content

Commit fbcfc8d

Browse files
authored
Update _formatted (#205)
1 parent c8e43ea commit fbcfc8d

File tree

4 files changed

+76
-64
lines changed

4 files changed

+76
-64
lines changed

examples/web_app/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ edition = "2018"
88
crate-type = ["cdylib", "rlib"]
99

1010
[dependencies]
11+
serde_json = "1.0"
1112
wasm-bindgen = "0.2"
1213
wasm-bindgen-futures = "0.4.18"
1314
yew = "0.18"

examples/web_app/src/document.rs

Lines changed: 45 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use meilisearch_sdk::document::Document;
22
use serde::{Deserialize, Serialize};
3+
use serde_json::{Map, Value};
34
use yew::prelude::*;
45

56
#[derive(Debug, Serialize, Deserialize)]
@@ -22,58 +23,56 @@ impl Document for Crate {
2223
}
2324
}
2425

25-
impl Crate {
26-
27-
pub fn get_readable_download_count(&self) -> String {
28-
if let Some(downloads) = self.downloads {
29-
if downloads < 1000 {
30-
downloads.to_string()
31-
} else if downloads < 1000000 {
32-
format!("{:.1}k", downloads as f64 / 1000.0)
33-
} else {
34-
format!("{:.1}M", downloads as f64 / 1000000.0)
35-
}
26+
27+
fn get_readable_download_count(this: &Map<String, Value>) -> String {
28+
if let Some(downloads) = this["downloads"].as_f64() {
29+
if downloads < 1000.0 {
30+
downloads.to_string()
31+
} else if downloads < 1000000.0 {
32+
format!("{:.1}k", downloads / 1000.0)
3633
} else {
37-
String::from("?")
34+
format!("{:.1}M", downloads / 1000000.0)
3835
}
36+
} else {
37+
String::from("?")
3938
}
39+
}
4040

41-
pub fn display(&self) -> Html {
42-
let mut url = format!("https://lib.rs/crates/{}", self.name);
43-
url = url.replace("<em>", "");
44-
url = url.replace("</em>", "");
41+
pub fn display(this: &Map<String, Value>) -> Html {
42+
let mut url = format!("https://lib.rs/crates/{}", this["name"].as_str().unwrap_or_default());
43+
url = url.replace("<em>", "");
44+
url = url.replace("</em>", "");
4545

46-
html! {
47-
<li><a href=url>
48-
<div class="h">
49-
<h4>
50-
{
51-
// This field is formatted so we don't want Yew to escape the HTML tags
52-
unescaped_html(&self.name)
53-
}
54-
</h4>
55-
<p class="desc">{unescaped_html(&self.description)}</p>
56-
</div>
57-
<div class="meta">
58-
<span class="version stable">
59-
<span>{"v"}</span>
60-
{&self.version}
61-
</span>
62-
<span class="downloads" title=format!("{} recent downloads", self.downloads.unwrap_or(0))>
63-
{self.get_readable_download_count()}
64-
</span>
65-
{for self.keywords.iter().map(|keyword|
66-
html! {
67-
<span class="k">
68-
<span>{"#"}</span>
69-
{keyword}
70-
</span>
71-
}
72-
)}
73-
</div>
46+
html! {
47+
<li><a href=url>
48+
<div class="h">
49+
<h4>
50+
{
51+
// This field is formatted so we don't want Yew to escape the HTML tags
52+
unescaped_html(&this["name"].as_str().unwrap_or_default())
53+
}
54+
</h4>
55+
<p class="desc">{unescaped_html(&this["description"].as_str().unwrap_or_default())}</p>
56+
</div>
57+
<div class="meta">
58+
<span class="version stable">
59+
<span>{"v"}</span>
60+
{&this["version"].as_str().unwrap_or_default()}
61+
</span>
62+
<span class="downloads" title=format!("{} recent downloads", this["downloads"].as_f64().unwrap_or(0.0))>
63+
{get_readable_download_count(this)}
64+
</span>
65+
{for this["keywords"].as_array().unwrap().iter().map(|keyword|
66+
html! {
67+
<span class="k">
68+
<span>{"#"}</span>
69+
{keyword.as_str().unwrap_or_default()}
70+
</span>
71+
}
72+
)}
73+
</div>
7474

75-
</a></li>
76-
}
75+
</a></li>
7776
}
7877
}
7978

examples/web_app/src/lib.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,15 @@ use meilisearch_sdk::{
44
indexes::Index,
55
search::{SearchResults, Selectors::All},
66
};
7+
use serde_json::{Map, Value};
78
use std::rc::Rc;
89
use wasm_bindgen::prelude::*;
910
use wasm_bindgen_futures::spawn_local;
1011
use yew::prelude::*;
1112
use lazy_static::lazy_static;
1213

1314
mod document;
14-
use crate::document::Crate;
15+
use crate::document::{Crate, display};
1516

1617
lazy_static! {
1718
static ref CLIENT: Client = Client::new(
@@ -23,7 +24,7 @@ lazy_static! {
2324
struct Model {
2425
link: Rc<ComponentLink<Self>>,
2526
index: Rc<Index>,
26-
results: Vec<Crate>,
27+
results: Vec<Map<String, Value>>,
2728
processing_time_ms: usize,
2829

2930
// These two fields are used to avoid rollbacks by giving an ID to each request
@@ -35,7 +36,7 @@ enum Msg {
3536
/// An event sent to update the results with a query
3637
Input(String),
3738
/// The event sent to display new results once they are received
38-
Update{results: Vec<Crate>, processing_time_ms: usize, request_id: usize},
39+
Update{results: Vec<Map<String, Value>>, processing_time_ms: usize, request_id: usize},
3940
}
4041

4142
impl Component for Model {
@@ -126,7 +127,7 @@ impl Component for Model {
126127
<ol id="handlebars-list">
127128
{
128129
// Display the results
129-
for self.results.iter().map(|r| r.display())
130+
for self.results.iter().map(|r| display(r))
130131
}
131132
</ol>
132133
</div>

src/search.rs

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use crate::{errors::Error, indexes::Index};
22
use serde::{de::DeserializeOwned, Deserialize, Serialize, Serializer};
3+
use serde_json::{Map, Value};
34
use std::collections::HashMap;
45

56
#[derive(Deserialize, Debug, PartialEq)]
@@ -17,7 +18,7 @@ pub struct SearchResult<T> {
1718
pub result: T,
1819
/// The formatted result.
1920
#[serde(rename = "_formatted")]
20-
pub formatted_result: Option<T>,
21+
pub formatted_result: Option<Map<String, Value>>,
2122
/// The object that contains information about the matches.
2223
#[serde(rename = "_matchesInfo")]
2324
pub matches_info: Option<HashMap<String, Vec<MatchRange>>>,
@@ -284,6 +285,7 @@ impl<'a> Query<'a> {
284285
mod tests {
285286
use crate::{client::*, document, search::*};
286287
use serde::{Deserialize, Serialize};
288+
use serde_json::{Map, Value};
287289
use std::thread::sleep;
288290
use std::time::Duration;
289291
use futures_await_test::async_test;
@@ -303,6 +305,14 @@ mod tests {
303305
}
304306
}
305307

308+
impl PartialEq<Map<String, Value>> for Document {
309+
fn eq(&self, rhs: &Map<String, Value>) -> bool {
310+
self.id.to_string() == rhs["id"]
311+
&& self.value == rhs["value"]
312+
&& self.kind == rhs["kind"]
313+
}
314+
}
315+
306316
#[allow(unused_must_use)]
307317
async fn setup_test_index<'a>(client: &'a Client, name: &'a str) -> Index {
308318
// try to delete
@@ -486,23 +496,23 @@ mod tests {
486496
query.with_query("lorem ipsum");
487497
query.with_attributes_to_crop(Selectors::All);
488498
let results: SearchResults<Document> = index.execute_query(&query).await.unwrap();
489-
assert_eq!(results.hits[0].formatted_result.as_ref().unwrap(), &Document {
499+
assert_eq!(&Document {
490500
id: 0,
491501
value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip".to_string(),
492502
kind: "text".to_string()
493-
});
503+
}, results.hits[0].formatted_result.as_ref().unwrap());
494504

495505
let mut query = Query::new(&index);
496506
query.with_query("lorem ipsum");
497507
query.with_attributes_to_crop(Selectors::Some(&[("value", Some(50)), ("kind", None)]));
498508
let results: SearchResults<Document> = index.execute_query(&query).await.unwrap();
499509
assert_eq!(
500-
results.hits[0].formatted_result.as_ref().unwrap(),
501510
&Document {
502511
id: 0,
503512
value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit".to_string(),
504513
kind: "text".to_string()
505-
}
514+
},
515+
results.hits[0].formatted_result.as_ref().unwrap()
506516
);
507517

508518
client
@@ -521,24 +531,25 @@ mod tests {
521531
query.with_attributes_to_crop(Selectors::All);
522532
query.with_crop_length(200);
523533
let results: SearchResults<Document> = index.execute_query(&query).await.unwrap();
524-
assert_eq!(results.hits[0].formatted_result.as_ref().unwrap(), &Document {
534+
assert_eq!(&Document {
525535
id: 0,
526536
value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip".to_string(),
527-
kind: "text".to_string()
528-
});
537+
kind: "text".to_string(),
538+
},
539+
results.hits[0].formatted_result.as_ref().unwrap());
529540

530541
let mut query = Query::new(&index);
531542
query.with_query("lorem ipsum");
532543
query.with_attributes_to_crop(Selectors::All);
533544
query.with_crop_length(50);
534545
let results: SearchResults<Document> = index.execute_query(&query).await.unwrap();
535546
assert_eq!(
536-
results.hits[0].formatted_result.as_ref().unwrap(),
537547
&Document {
538548
id: 0,
539549
value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit".to_string(),
540550
kind: "text".to_string()
541-
}
551+
},
552+
results.hits[0].formatted_result.as_ref().unwrap()
542553
);
543554

544555
client.delete_index("test_query_crop_lenght").await.unwrap();
@@ -554,25 +565,25 @@ mod tests {
554565
query.with_attributes_to_highlight(Selectors::All);
555566
let results: SearchResults<Document> = index.execute_query(&query).await.unwrap();
556567
assert_eq!(
557-
results.hits[0].formatted_result.as_ref().unwrap(),
558568
&Document {
559569
id: 1,
560570
value: "<em>dolor</em> sit amet, consectetur adipiscing elit".to_string(),
561571
kind: "<em>text</em>".to_string()
562-
}
572+
},
573+
results.hits[0].formatted_result.as_ref().unwrap(),
563574
);
564575

565576
let mut query = Query::new(&index);
566577
query.with_query("dolor text");
567578
query.with_attributes_to_highlight(Selectors::Some(&["value"]));
568579
let results: SearchResults<Document> = index.execute_query(&query).await.unwrap();
569580
assert_eq!(
570-
results.hits[0].formatted_result.as_ref().unwrap(),
571581
&Document {
572582
id: 1,
573583
value: "<em>dolor</em> sit amet, consectetur adipiscing elit".to_string(),
574584
kind: "text".to_string()
575-
}
585+
},
586+
results.hits[0].formatted_result.as_ref().unwrap()
576587
);
577588

578589
client

0 commit comments

Comments
 (0)