sea_orm_newtype_id_domain/
lib.rs

1use nanoid::nanoid;
2
3/// Id generation lives here
4#[derive(Debug)]
5pub struct Id;
6
7impl Id {
8    /// Generates an ID with a prefix
9    pub fn generate(prefix: &str) -> String {
10        debug_assert!(prefix.len() <= 4);
11
12        let id = nanoid!();
13        format!("{}_{}", prefix, id)
14    }
15}
16
17/// PrefixId
18///
19/// Is a trait that is used to add prefix based ID generation to a given domain
20/// object, e.g. an object that gets inserted into the database
21pub trait PrefixedId {
22    /// The prefix that is desired
23    const PREFIX: &'static str;
24
25    /// Generated a new id with the given prefix
26    fn new_id() -> String {
27        Id::generate(Self::PREFIX)
28    }
29
30    /// Return the prefix
31    fn id_prefix() -> String {
32        Self::PREFIX.to_string()
33    }
34}
35
36/// Error for parsing
37#[derive(Clone, Debug)]
38pub struct ParseIdError {
39    pub typename: &'static str,
40    pub expected: &'static str,
41}
42
43impl std::fmt::Display for ParseIdError {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        write!(f, "invalid `{}`, expected {}", self.typename, self.expected)
46    }
47}
48
49impl std::error::Error for ParseIdError {
50    fn description(&self) -> &str {
51        "error parsing an id"
52    }
53}