forked from jmug/stoatchat
feat(core/database): add Reference struct
This commit is contained in:
1
crates/core/database/src/util/mod.rs
Normal file
1
crates/core/database/src/util/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod reference;
|
||||
52
crates/core/database/src/util/reference.rs
Normal file
52
crates/core/database/src/util/reference.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use revolt_result::Result;
|
||||
#[cfg(feature = "rocket-impl")]
|
||||
use rocket::request::FromParam;
|
||||
#[cfg(feature = "rocket-impl")]
|
||||
use schemars::{
|
||||
schema::{InstanceType, Schema, SchemaObject, SingleOrVec},
|
||||
JsonSchema,
|
||||
};
|
||||
|
||||
use crate::{Bot, Database};
|
||||
|
||||
/// Reference to some object in the database
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Reference {
|
||||
/// Id of object
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
impl Reference {
|
||||
/// Create a Ref from an unchecked string
|
||||
pub fn from_unchecked(id: String) -> Reference {
|
||||
Reference { id }
|
||||
}
|
||||
|
||||
/// Fetch bot from Ref
|
||||
pub async fn as_bot(&self, db: &Database) -> Result<Bot> {
|
||||
db.fetch_bot(&self.id).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rocket-impl")]
|
||||
impl<'r> FromParam<'r> for Reference {
|
||||
type Error = &'r str;
|
||||
|
||||
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
|
||||
Ok(Reference::from_unchecked(param.into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rocket-impl")]
|
||||
impl JsonSchema for Reference {
|
||||
fn schema_name() -> String {
|
||||
"Id".to_string()
|
||||
}
|
||||
|
||||
fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> Schema {
|
||||
Schema::Object(SchemaObject {
|
||||
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user