kv_crud_core/
lib.rs

1use std::fmt::Debug;
2
3/// Represents an entity that can be stored in the system.
4/// You have to implement this trait for your custom type to be able to store it.
5/// Keep in mind that different implementations may require additional type constraints.
6pub trait Entity<IdType>: Clone + Debug {
7    fn get_id(&self) -> IdType;
8}
9
10/// Represents ability to save entity in the storage.
11/// This trait is used by custom storage implementations.
12pub trait Create<I, E: Entity<I>> {
13    type Error;
14    fn save(&mut self, entity: &E) -> Result<(), Self::Error>;
15}
16
17/// Represents the ability to find single entity by its id in the system.
18/// This trait is used by custom storage implementations.
19pub trait Read<I, E: Entity<I>> {
20    type Error;
21    fn find_by_id(&self, id: &I) -> Result<E, Self::Error>;
22}
23
24/// Represents the ability to list items with pagination and sorting.
25/// This trait is used by custom storage implementations.
26pub trait ReadWithPaginationAndSort<I, E: Entity<I>> {
27    type Error;
28    fn find_all_with_page(&self, page: &Page) -> Result<Vec<E>, Self::Error>;
29    fn find_all_with_page_and_sort(&self, page: &Page, sort: &Sort) -> Result<Vec<E>, Self::Error>;
30}
31
32/// Represents the ability to update the entity.
33/// This trait is used by custom storage implementations.
34pub trait Update<I, E: Entity<I>> {
35    type Error;
36    fn update(&mut self, entity: &E) -> Result<(), Self::Error>;
37}
38
39/// Represents the ability to remove the entity from the storage.
40/// This trait is used by custom storage implementations.
41pub trait Delete<I, E: Entity<I>> {
42    type Error;
43    fn remove_by_id(&mut self, id: &I) -> Result<(), Self::Error>;
44    fn remove(&mut self, entity: &E) -> Result<(), Self::Error>;
45}
46
47pub trait Crud<I, E: Entity<I>>:
48    Create<I, E> + Read<I, E> + ReadWithPaginationAndSort<I, E> + Update<I, E> + Delete<I, E>
49{
50}
51
52/// Used for result pagination.
53pub struct Page {
54    /// Page number (starting from 0)
55    pub number: u32,
56    /// Results per page
57    pub size: u32,
58}
59
60impl Page {
61    /// Creates new page
62    pub fn new(number: u32, size: u32) -> Self {
63        Self { number, size }
64    }
65
66    /// Calculates the offset for given page
67    pub fn offset(&self) -> u32 {
68        self.number * self.size
69    }
70}
71
72/// Determines sorting order
73#[derive(PartialEq)]
74pub enum Sort {
75    ASCENDING,
76    DESCENDING,
77}