move list func into macro

This commit is contained in:
Manuel Gugger 2022-04-26 12:38:39 +02:00
parent 7648c4bced
commit 9923ae6a69
7 changed files with 53 additions and 104 deletions

View File

@ -6,34 +6,44 @@ pub fn derive_crud_fns(_input: proc_macro::TokenStream) -> proc_macro::TokenStre
let expanded = quote! {
use std::convert::From;
use async_trait::async_trait;
use std::pin::Pin;
use actix_admin::{ ActixAdminModelTrait, ActixAdminModel };
use actix_web::{web, HttpResponse, HttpRequest, Error};
use actix_admin::{ ActixAdminModelTrait, ActixAdminViewModelTrait, ActixAdminViewModel, ActixAdminModel, AppDataTrait };
// impl From<Entity> for ActixAdminModel {
// fn from(entity: Entity) -> Self {
// ActixAdminModel {
// fields: Vec::new()
// }
// }
// }
// #[async_trait]
// impl ActixAdminModelTrait for Entity {
// async fn list(&self, db: &DatabaseConnection, page: usize, posts_per_page: usize) -> Vec<&str> {
// use sea_orm::{ query::* };
// let paginator = Entity::find()
// .order_by_asc(Column::Id)
// .paginate(db, posts_per_page);
// let entities = paginator
// .fetch_page(page - 1)
// .await
// .expect("could not retrieve entities");
// //entities to ActixAdminModel
// vec![
// ]
// }
// }
impl From<Entity> for ActixAdminViewModel {
fn from(entity: Entity) -> Self {
ActixAdminViewModel {
entity_name: entity.table_name().to_string()
}
}
}
#[async_trait]
impl ActixAdminModelTrait for Entity {
async fn list_db(db: &DatabaseConnection, page: usize, posts_per_page: usize) -> Vec<&str> {
use sea_orm::{ query::* };
let paginator = Entity::find()
.order_by_asc(Column::Id)
.paginate(db, posts_per_page);
let entities = paginator
.fetch_page(page - 1)
.await
.expect("could not retrieve entities");
//entities to ActixAdminModel
vec![
]
}
}
#[async_trait(?Send)]
impl ActixAdminViewModelTrait for Entity {
async fn list<T: AppDataTrait>(req: HttpRequest, data: web::Data<T>) -> Result<HttpResponse, Error> {
let db = &data.get_db();
let entities = Entity::list_db(db, 1, 5);
let model = ActixAdminViewModel::from(Entity);
actix_admin::list_model(req, model)
}
}
};
proc_macro::TokenStream::from(expanded)

View File

@ -45,7 +45,7 @@ pub trait AppDataTrait {
// ActixAdminModel
#[async_trait]
pub trait ActixAdminModelTrait: Clone {
async fn list(db: &DatabaseConnection, page: usize, posts_per_page: usize) -> Vec<&str>;
async fn list_db(db: &DatabaseConnection, page: usize, posts_per_page: usize) -> Vec<&str>;
}
#[derive(Clone, Debug, Serialize)]
@ -54,8 +54,9 @@ pub struct ActixAdminModel {
}
// ActixAdminViewModel
pub trait ActixAdminViewModelTrait: Clone {
fn get_model_name(&self) -> &str;
#[async_trait(?Send)]
pub trait ActixAdminViewModelTrait {
async fn list<T: AppDataTrait + Sync + Send>(req: HttpRequest, data: web::Data<T>) -> Result<HttpResponse, Error>;
}
#[derive(Clone, Debug, Serialize)]
@ -103,8 +104,10 @@ pub fn list_model(req: HttpRequest, view_model: ActixAdminViewModel) -> Result<H
let columns: Vec<String> = Vec::new();
let entities: Vec<&str> = Vec::new(); // view_model.get_entities()
let view_models: Vec<&str> = Vec::new();
let mut ctx = Context::new();
ctx.insert("view_models", &view_models);
ctx.insert("posts", &entities);
ctx.insert("page", &page);
ctx.insert("posts_per_page", &posts_per_page);
@ -113,6 +116,6 @@ pub fn list_model(req: HttpRequest, view_model: ActixAdminViewModel) -> Result<H
let body = TERA
.render("list.html", &ctx)
.map_err(|_| error::ErrorInternalServerError("Template error"))?;
.map_err(|err| error::ErrorInternalServerError(err))?;
Ok(HttpResponse::Ok().content_type("text/html").body(body))
}

View File

@ -2,8 +2,4 @@
{% block content %}
Hello
<p>posts: {{ posts }}</p>
<p>page: {{ page }}</p>
<p>posts_per_page: {{ posts_per_page }}</p>
<p>num_pages: {{ num_pages }}</p>
{% endblock content %}

View File

@ -17,31 +17,4 @@ pub struct Model {
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
impl From<Entity> for ActixAdminModel {
fn from(entity: Entity) -> Self {
ActixAdminModel {
fields: Vec::new()
}
}
}
#[async_trait]
impl ActixAdminModelTrait for Entity {
async fn list(&self, db: &DatabaseConnection, page: usize, posts_per_page: usize) -> Vec<&str> {
use sea_orm::{ query::* };
let paginator = Entity::find()
.order_by_asc(Column::Id)
.paginate(db, posts_per_page);
let entities = paginator
.fetch_page(page - 1)
.await
.expect("could not retrieve entities");
//entities to ActixAdminModel
vec![
]
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@ -2,7 +2,9 @@
use sea_orm::sea_query::{ColumnDef, TableCreateStatement};
use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult};
pub mod post;
pub mod comment;
pub use post::Entity as Post;
pub use comment::Entity as Comment;
// setup
async fn create_table(db: &DbConn, stmt: &TableCreateStatement) -> Result<ExecResult, DbErr> {

View File

@ -1,7 +1,6 @@
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
use actix_admin::{ DeriveActixAdminModel, ActixAdminViewModel };
use actix_admin::{ DeriveActixAdminModel };
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize, DeriveActixAdminModel)]
#[sea_orm(table_name = "post")]
@ -17,30 +16,4 @@ pub struct Model {
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
impl From<Entity> for ActixAdminViewModel {
fn from(entity: Entity) -> Self {
ActixAdminViewModel {
entity_name: entity.table_name().to_string()
}
}
}
#[async_trait]
impl ActixAdminModelTrait for Entity {
async fn list(db: &DatabaseConnection, page: usize, posts_per_page: usize) -> Vec<&str> {
use sea_orm::{ query::* };
let paginator = Entity::find()
.order_by_asc(Column::Id)
.paginate(db, posts_per_page);
let entities = paginator
.fetch_page(page - 1)
.await
.expect("could not retrieve entities");
//entities to ActixAdminModel
vec![
]
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@ -8,12 +8,12 @@ use oauth2::{ RedirectUrl };
use std::time::{Duration};
use std::env;
use sea_orm::{{ DatabaseConnection, ConnectOptions }};
use actix_admin::{ AppDataTrait as ActixAdminAppDataTrait, ActixAdminViewModel, ActixAdminModelTrait};
use std::any::Any;
use actix_admin::{ AppDataTrait as ActixAdminAppDataTrait, ActixAdminViewModelTrait };
use azure_auth::{ AzureAuth, UserInfo, AppDataTrait as AzureAuthAppDataTrait };
mod entity;
use entity::{ Post };
use entity::{ Post, Comment };
#[derive(Debug, Clone)]
pub struct AppState {
@ -92,7 +92,7 @@ async fn main() {
actix_admin::ActixAdmin::new()
.create_scope(&app_state)
.service(
web::scope(&format!("/{}", "posts")).route("/list", web::get().to(list)),
web::scope(&format!("/{}", "posts")).route("/list", web::get().to(Post::list::<AppState>)),
)
)
})
@ -101,12 +101,4 @@ async fn main() {
.run()
.await
.unwrap();
}
// Actix admin Routes to be auto generated
async fn list(req: HttpRequest, data: web::Data<AppState>)-> Result<HttpResponse, Error> {
let db = &data.get_db();
let entities = Post::list(db, 1, 5);
let model = ActixAdminViewModel::from(Post);
actix_admin::list_model(req, model)
}