mirror of
https://github.com/flibusta-apps/book_library_server.git
synced 2025-12-06 15:15:36 +01:00
Fix
This commit is contained in:
31
src/views/common/get_random_item.rs
Normal file
31
src/views/common/get_random_item.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use meilisearch_sdk::indexes::Index;
|
||||
use rand::Rng;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::meilisearch::GetId;
|
||||
|
||||
pub async fn get_random_item<'a, T>(
|
||||
index: Index, filter: String,
|
||||
) -> i32
|
||||
where T: DeserializeOwned + GetId + 'static {
|
||||
let result = index
|
||||
.search()
|
||||
.with_filter(&filter)
|
||||
.execute::<T>()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let offset: usize = rand::thread_rng().gen_range(0..result.estimated_total_hits.unwrap().try_into().unwrap());
|
||||
|
||||
let result = index
|
||||
.search()
|
||||
.with_limit(1)
|
||||
.with_offset(offset)
|
||||
.execute::<T>()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let item = &result.hits.get(0).unwrap().result;
|
||||
|
||||
item.get_id()
|
||||
}
|
||||
Reference in New Issue
Block a user