70 lines
2.0 KiB
Rust
70 lines
2.0 KiB
Rust
use crate::models::{Index, Model};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
pub mod fjall;
|
|
pub mod hero;
|
|
|
|
pub trait Db {
|
|
/// Error type returned by database operations.
|
|
type Error: std::fmt::Debug;
|
|
|
|
/// Open the collection for a specific model. This method must create the collection if it does not exist.
|
|
fn collection<M: Model>(&self) -> Result<impl Collection<&str, M>, Error<Self::Error>>;
|
|
}
|
|
|
|
/// A collection stores a specific model under a specific key
|
|
pub trait Collection<K, V>
|
|
where
|
|
K: Serialize,
|
|
V: Serialize + for<'a> Deserialize<'a>,
|
|
{
|
|
/// Error type for database operations
|
|
type Error: std::fmt::Debug;
|
|
|
|
/// Get all items where the given index field is equal to key.
|
|
fn get<I>(&self, key: K) -> Result<Vec<V>, Error<Self::Error>>
|
|
where
|
|
I: Index<Model = V>;
|
|
|
|
/// Get an object from its ID. This does not use an index lookup
|
|
fn get_by_id(&self, id: u32) -> Result<Option<V>, Error<Self::Error>>;
|
|
|
|
/// Store an item in the DB.
|
|
fn set(&self, value: &V) -> Result<(), Error<Self::Error>>;
|
|
|
|
/// Delete all items from the db with a given index.
|
|
fn delete<I>(&self, key: K) -> Result<(), Error<Self::Error>>
|
|
where
|
|
I: Index<Model = V>;
|
|
|
|
/// Delete an object with a given ID
|
|
fn delete_by_id(&self, id: u32) -> Result<(), Error<Self::Error>>;
|
|
|
|
/// Get all objects from the colelction
|
|
fn get_all(&self) -> Result<Vec<V>, Error<Self::Error>>;
|
|
}
|
|
|
|
/// Errors returned by the DB implementation
|
|
#[derive(Debug)]
|
|
pub enum Error<E> {
|
|
/// Error in the underlying database
|
|
DB(E),
|
|
/// Error decoding a stored model
|
|
Decode(bincode::error::DecodeError),
|
|
/// Error encoding a model for storage
|
|
Encode(bincode::error::EncodeError),
|
|
}
|
|
|
|
impl<E> From<bincode::error::DecodeError> for Error<E> {
|
|
fn from(value: bincode::error::DecodeError) -> Self {
|
|
Error::Decode(value)
|
|
}
|
|
}
|
|
|
|
impl<E> From<bincode::error::EncodeError> for Error<E> {
|
|
fn from(value: bincode::error::EncodeError) -> Self {
|
|
Error::Encode(value)
|
|
}
|
|
}
|
|
|