Add function to read all orders

This commit is contained in:
~erin 2022-04-01 13:01:07 -04:00
parent 233cc25371
commit 3928f50be5
No known key found for this signature in database
GPG Key ID: DA70E064A8C70F44
1 changed files with 42 additions and 1 deletions

View File

@ -6,7 +6,6 @@ use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::path::PathBuf;
// Open the database
pub fn open_database(keyspace: &str) -> Option<sled::Tree> {
let db: sled::Db;
@ -93,6 +92,48 @@ pub fn read_product(short_name: &str) -> Result<Product, sled::Error> {
};
}
// Read all products pushed to the database
pub fn read_all_products() -> Result<Vec<Product>, sled::Error> {
let db = match open_database("products") {
Some(database) => database,
None => panic!(),
};
info!("Reading all products from database");
let first_key = match db.first() {
Ok(key) => match key {
Some(v) => v.0,
None => {
return Err(sled::Error::Unsupported(
sled::Error::ReportableBug("product not found".to_string()).to_string(),
));
}
},
Err(error) => return Err(error),
}; // Get the first key from the database
let iter = db.range(first_key..); // Create an iterator of all keys from the first one
let mut all_products: Vec<Product> = Vec::new(); // Create a new vector to store the orders
for product in iter {
// Iterate over the orders
if let product_entry = product.unwrap().1 {
// If we can unwrap it:
let read_product: Product = match bincode::deserialize(&product_entry) {
Ok(product) => product,
Err(error) => panic!("could not deserialize product: {:?}", error),
}; // Deserialize the entry
all_products.push(read_product); // Add the entry to the vector
} else {
// Fail
warn!("Could not find any more products");
db.flush().unwrap();
}
}
return Ok(all_products); // Return the orders
}
// Create a new order
pub fn make_order(order: &Order) -> Result<String, sled::Error> {
info!(