Created
November 12, 2020 15:13
-
-
Save wess/124dcbe7130f684cb99f9ccca31f2edf to your computer and use it in GitHub Desktop.
Feed backs, please
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use serde::{Serialize}; | |
use mongodb::bson::{ | |
to_bson, | |
Bson, | |
}; | |
pub trait Model : Serialize { | |
fn to_bson(&self) -> Bson { | |
to_bson(self).unwrap() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use async_trait::async_trait; | |
use mongodb::{ | |
error::Error, | |
Collection, | |
results::{ | |
InsertOneResult | |
} | |
}; | |
use crate::db::Connection; | |
use crate::models::Model; | |
#[async_trait] | |
pub trait Provider<T:Model + std::marker::Sync + std::marker::Send> { | |
fn init(conn:&Connection) -> Self; | |
fn get_collection(&self) -> &Collection; | |
async fn save<'a>(&self, model: &'a T) -> Result<InsertOneResult, Error> { | |
self.get_collection().insert_one( | |
model.to_bson().as_document().unwrap().clone(), | |
None | |
).await | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use serde::{Deserialize, Serialize}; | |
use mongodb::bson::{ | |
oid::ObjectId | |
}; | |
use super::model::Model; | |
#[derive(Serialize, Deserialize, Clone, Debug)] | |
pub struct User { | |
#[serde(rename="_id", skip_serializing_if="Option::is_none")] | |
pub id:Option<ObjectId>, | |
pub login:String, | |
pub email:String, | |
pub avatar:String, | |
pub token:String, | |
} | |
impl Model for User {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use mongodb::{ | |
Collection, | |
}; | |
use super::provider::Provider; | |
use crate::db::Connection; | |
use crate::models::User; | |
pub struct UserProvider { | |
collection:Collection | |
} | |
impl Provider<User> for UserProvider { | |
fn init(conn:&Connection) -> Self { | |
Self { | |
collection: conn.database.collection("users") | |
} | |
} | |
fn get_collection(&self) -> &Collection { | |
&self.collection | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment