Skip to content

Instantly share code, notes, and snippets.

@wess
Created November 12, 2020 15:13
Show Gist options
  • Save wess/124dcbe7130f684cb99f9ccca31f2edf to your computer and use it in GitHub Desktop.
Save wess/124dcbe7130f684cb99f9ccca31f2edf to your computer and use it in GitHub Desktop.
Feed backs, please
use serde::{Serialize};
use mongodb::bson::{
to_bson,
Bson,
};
pub trait Model : Serialize {
fn to_bson(&self) -> Bson {
to_bson(self).unwrap()
}
}
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
}
}
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 {}
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