Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make AppContext extensible via traits #777

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/demo/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions examples/demo/examples/playground.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use demo_app::app::App;
#[allow(unused_imports)]
use loco_rs::{cli::playground, prelude::*};
use loco_rs::{app::AppContext, cli::playground, prelude::*};

#[tokio::main]
async fn main() -> loco_rs::Result<()> {
let _ctx = playground::<App>().await?;
let _ctx = playground::<AppContext, App>().await?;

// let active_model: articles::ActiveModel = ActiveModel {
// title: Set(Some("how to build apps in 3 steps".to_string())),
Expand Down
6 changes: 4 additions & 2 deletions examples/demo/examples/start.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use demo_app::app::App;
use loco_rs::{
app::AppContext,
boot::{create_app, start, ServeParams, StartMode},
environment::{resolve_from_env, Environment},
};
Expand All @@ -9,11 +10,12 @@ use migration::Migrator;
async fn main() -> loco_rs::Result<()> {
let environment: Environment = resolve_from_env().into();

let boot_result = create_app::<App, Migrator>(StartMode::ServerAndWorker, &environment).await?;
let boot_result =
create_app::<AppContext, App, Migrator>(StartMode::ServerAndWorker, &environment).await?;
let serve_params = ServeParams {
port: boot_result.app_context.config.server.port,
binding: boot_result.app_context.config.server.binding.to_string(),
};
start::<App>(boot_result, serve_params).await?;
start::<AppContext, App>(boot_result, serve_params).await?;
Ok(())
}
5 changes: 3 additions & 2 deletions examples/demo/examples/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::env;

use demo_app::app::App;
use loco_rs::{
app::AppContext,
boot::{create_context, run_task},
environment::{resolve_from_env, Environment},
task,
Expand All @@ -13,8 +14,8 @@ async fn main() -> loco_rs::Result<()> {

let args = env::args().collect::<Vec<_>>();
let cmd = args.get(1);
let app_context = create_context::<App>(&environment).await?;
run_task::<App>(&app_context, cmd, &task::Vars::default()).await?;
let app_context = create_context::<AppContext, App>(&environment).await?;
run_task::<AppContext, App>(&app_context, cmd, &task::Vars::default()).await?;

Ok(())
}
6 changes: 4 additions & 2 deletions examples/demo/examples/workers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use demo_app::app::App;
use loco_rs::{
app::AppContext,
boot::{create_app, start, ServeParams, StartMode},
environment::{resolve_from_env, Environment},
};
Expand All @@ -9,11 +10,12 @@ use migration::Migrator;
async fn main() -> loco_rs::Result<()> {
let environment: Environment = resolve_from_env().into();

let boot_result = create_app::<App, Migrator>(StartMode::WorkerOnly, &environment).await?;
let boot_result =
create_app::<AppContext, App, Migrator>(StartMode::WorkerOnly, &environment).await?;
let serve_params = ServeParams {
port: boot_result.app_context.config.server.port,
binding: boot_result.app_context.config.server.binding.to_string(),
};
start::<App>(boot_result, serve_params).await?;
start::<AppContext, App>(boot_result, serve_params).await?;
Ok(())
}
8 changes: 4 additions & 4 deletions examples/demo/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::{

pub struct App;
#[async_trait]
impl Hooks for App {
impl Hooks<AppContext> for App {
fn app_version() -> String {
format!(
"{} ({})",
Expand Down Expand Up @@ -61,7 +61,7 @@ impl Hooks for App {
}
// </snip>

fn routes(ctx: &AppContext) -> AppRoutes {
fn routes(ctx: &AppContext) -> AppRoutes<AppContext> {
AppRoutes::with_default_routes()
.add_route(
controllers::mylayer::routes(ctx.clone())
Expand All @@ -77,8 +77,8 @@ impl Hooks for App {
.add_route(controllers::cache::routes())
}

async fn boot(mode: StartMode, environment: &Environment) -> Result<BootResult> {
create_app::<Self, Migrator>(mode, environment).await
async fn boot(mode: StartMode, environment: &Environment) -> Result<BootResult<AppContext>> {
create_app::<AppContext, Self, Migrator>(mode, environment).await
}

async fn after_context(ctx: AppContext) -> Result<AppContext> {
Expand Down
4 changes: 2 additions & 2 deletions examples/demo/src/bin/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use demo_app::app::App;
use loco_rs::cli;
use loco_rs::{app::AppContext, cli};
use migration::Migrator;

#[tokio::main]
async fn main() -> loco_rs::Result<()> {
cli::main::<App, Migrator>().await
cli::main::<AppContext, App, Migrator>().await
}
4 changes: 2 additions & 2 deletions examples/demo/src/bin/tool.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use demo_app::app::App;
use loco_rs::cli;
use loco_rs::{app::AppContext, cli};
use migration::Migrator;

#[tokio::main]
async fn main() -> loco_rs::Result<()> {
cli::main::<App, Migrator>().await
cli::main::<AppContext, App, Migrator>().await
}
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ async fn login(State(ctx): State<AppContext>, Json(params): Json<LoginParams>) -
format::json(UserSession::new(&user, &token))
}

pub fn routes() -> Routes {
pub fn routes() -> Routes<AppContext> {
Routes::new()
.prefix("auth")
.add("/register", post(register))
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async fn get_or_insert(State(ctx): State<AppContext>) -> Result<Response> {
}
}

pub fn routes() -> Routes {
pub fn routes() -> Routes<AppContext> {
Routes::new()
.prefix("cache")
.add("/", get(get_cache))
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/mylayer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ async fn echo() -> Result<Response> {
format::json("Hello, World!")
}

pub fn routes(ctx: AppContext) -> Routes {
pub fn routes(ctx: AppContext) -> Routes<AppContext> {
Routes::new()
.prefix("mylayer")
// Only users with the RoleName::Admin can access this route
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/mysession.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ pub async fn get_session(_session: Session<SessionNullPool>) -> Result<Response>
format::empty()
}

pub fn routes() -> Routes {
pub fn routes() -> Routes<AppContext> {
Routes::new().prefix("mysession").add("/", get(get_session))
}
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/notes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ impl ListQueryParams {
}
}

pub fn routes() -> Routes {
pub fn routes() -> Routes<AppContext> {
Routes::new()
.prefix("notes")
.add("/", get(list))
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ pub async fn set_cookie() -> Result<Response> {
format::render().cookies(&[cookie])?.json(())
}

pub fn routes() -> Routes {
pub fn routes() -> Routes<AppContext> {
Routes::new()
.prefix("response")
.add("/empty", get(empty))
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async fn upload_file(State(ctx): State<AppContext>, mut multipart: Multipart) ->
})
}

pub fn routes() -> Routes {
pub fn routes() -> Routes<AppContext> {
Routes::new()
.prefix("upload")
.add("/file", post(upload_file))
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async fn convert_to_user(
format::json(UserResponse::new(&auth.user, &roles))
}

pub fn routes() -> Routes {
pub fn routes() -> Routes<AppContext> {
Routes::new()
.prefix("user")
.add("/current", get(current))
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/src/controllers/view_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub async fn render_simple() -> Result<Response> {
format::render().template("{{name}} website", json!({"name": "Loco"}))
}

pub fn routes() -> Routes {
pub fn routes() -> Routes<AppContext> {
Routes::new()
.prefix("view-engine")
.add("/home", get(render_home))
Expand Down
4 changes: 2 additions & 2 deletions examples/demo/src/initializers/axum_session.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use async_trait::async_trait;
use axum::Router as AxumRouter;
use loco_rs::prelude::*;
use loco_rs::{app::Context, prelude::*};

pub struct AxumSessionInitializer;

Expand All @@ -10,7 +10,7 @@ impl Initializer for AxumSessionInitializer {
"axum-session".to_string()
}

async fn after_routes(&self, router: AxumRouter, _ctx: &AppContext) -> Result<AxumRouter> {
async fn after_routes(&self, router: AxumRouter, _ctx: &dyn Context) -> Result<AxumRouter> {
let session_config =
axum_session::SessionConfig::default().with_table_name("sessions_table");

Expand Down
4 changes: 2 additions & 2 deletions examples/demo/src/initializers/hello_view_engine.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use axum::{async_trait, Extension, Router as AxumRouter};
use loco_rs::{
app::{AppContext, Initializer},
app::{AppContext, Context, Initializer},
controller::views::{ViewEngine, ViewRenderer},
Result,
};
Expand All @@ -21,7 +21,7 @@ impl Initializer for HelloViewEngineInitializer {
"custom-view-engine".to_string()
}

async fn after_routes(&self, router: AxumRouter, _ctx: &AppContext) -> Result<AxumRouter> {
async fn after_routes(&self, router: AxumRouter, _ctx: &dyn Context) -> Result<AxumRouter> {
Ok(router.layer(Extension(ViewEngine::from(HelloView))))
}
}
4 changes: 2 additions & 2 deletions examples/demo/src/initializers/view_engine.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use axum::{async_trait, Extension, Router as AxumRouter};
use fluent_templates::{ArcLoader, FluentLoader};
use loco_rs::{
app::{AppContext, Initializer},
app::{AppContext, Context, Initializer},
controller::views::{engines, ViewEngine},
Error, Result,
};
Expand All @@ -17,7 +17,7 @@ impl Initializer for ViewEngineInitializer {
"view-engine".to_string()
}

async fn after_routes(&self, router: AxumRouter, _ctx: &AppContext) -> Result<AxumRouter> {
async fn after_routes(&self, router: AxumRouter, _ctx: &dyn Context) -> Result<AxumRouter> {
let mut tera_engine = engines::TeraView::build()?;
if std::path::Path::new(I18N_DIR).exists() {
let arc = ArcLoader::builder(&I18N_DIR, unic_langid::langid!("en-US"))
Expand Down
4 changes: 2 additions & 2 deletions examples/demo/src/tasks/foo.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// <snip id="task-code-example" />
use loco_rs::prelude::*;
use loco_rs::{app::Context, prelude::*};

pub struct Foo;
#[async_trait]
Expand All @@ -10,7 +10,7 @@ impl Task for Foo {
detail: "run foo task".to_string(),
}
}
async fn run(&self, _app_context: &AppContext, _vars: &task::Vars) -> Result<()> {
async fn run(&self, _app_context: &dyn Context, _vars: &task::Vars) -> Result<()> {
Ok(())
}
}
Expand Down
8 changes: 4 additions & 4 deletions examples/demo/src/tasks/seed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
//! command with the `refresh:true` argument: ```sh
//! cargo run task seed_data refresh:true
//! ```
use loco_rs::{db, prelude::*};
use loco_rs::{app::Context, db, prelude::*};
use migration::Migrator;

use crate::app::App;
Expand All @@ -27,16 +27,16 @@ impl Task for SeedData {
detail: "Task for seeding data".to_string(),
}
}
async fn run(&self, app_context: &AppContext, vars: &task::Vars) -> Result<()> {
async fn run(&self, app_context: &dyn Context, vars: &task::Vars) -> Result<()> {
let refresh = vars
.cli_arg("refresh")
.is_ok_and(|refresh| refresh == "true");

if refresh {
db::reset::<Migrator>(&app_context.db).await?;
db::reset::<Migrator>(app_context.db()).await?;
}
let path = std::path::Path::new("src/fixtures");
db::run_app_seed::<App>(&app_context.db, path).await?;
db::run_app_seed::<AppContext, App>(app_context.db(), path).await?;
Ok(())
}
}
6 changes: 3 additions & 3 deletions examples/demo/src/tasks/user_report.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use loco_rs::prelude::*;
use loco_rs::{app::Context, prelude::*};

use crate::models::_entities::users;

Expand All @@ -11,8 +11,8 @@ impl Task for UserReport {
detail: "output a user report".to_string(),
}
}
async fn run(&self, app_context: &AppContext, vars: &task::Vars) -> Result<()> {
let users = users::Entity::find().all(&app_context.db).await?;
async fn run(&self, app_context: &dyn Context, vars: &task::Vars) -> Result<()> {
let users = users::Entity::find().all(app_context.db()).await?;
println!("args: {vars:?}");
println!("!!! user_report: listing users !!!");
println!("------------------------");
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/src/workers/downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub struct DownloadWorkerArgs {
pub user_guid: String,
}

impl worker::AppWorker<DownloadWorkerArgs> for DownloadWorker {
impl worker::AppWorker<AppContext, DownloadWorkerArgs> for DownloadWorker {
fn build(ctx: &AppContext) -> Self {
Self { ctx: ctx.clone() }
}
Expand Down
12 changes: 6 additions & 6 deletions examples/demo/tests/models/roles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use demo_app::{
app::App,
models::{roles, sea_orm_active_enums, users, users::RegisterParams, users_roles},
};
use loco_rs::{prelude::*, testing};
use loco_rs::{app::AppContext, prelude::*, testing};
use sea_orm::DatabaseConnection;
use serial_test::serial;

Expand All @@ -20,7 +20,7 @@ macro_rules! configure_insta {
async fn can_add_user_to_admin() {
configure_insta!();

let boot = testing::boot_test::<App>().await.unwrap();
let boot = testing::boot_test::<AppContext, App>().await.unwrap();
let new_user: Result<users::Model, ModelError> = users::Model::create_with_password(
&boot.app_context.db,
&RegisterParams {
Expand All @@ -42,7 +42,7 @@ async fn can_add_user_to_admin() {
async fn can_add_user_to_user() {
configure_insta!();

let boot = testing::boot_test::<App>().await.unwrap();
let boot = testing::boot_test::<AppContext, App>().await.unwrap();
let new_user: Result<users::Model, ModelError> = users::Model::create_with_password(
&boot.app_context.db,
&RegisterParams {
Expand All @@ -64,7 +64,7 @@ async fn can_add_user_to_user() {
async fn can_convert_between_user_and_admin() {
configure_insta!();

let boot = testing::boot_test::<App>().await.unwrap();
let boot = testing::boot_test::<AppContext, App>().await.unwrap();
let new_user: Result<users::Model, ModelError> = users::Model::create_with_password(
&boot.app_context.db,
&RegisterParams {
Expand Down Expand Up @@ -94,7 +94,7 @@ async fn can_convert_between_user_and_admin() {
async fn can_find_user_roles() {
configure_insta!();

let boot = testing::boot_test::<App>().await.unwrap();
let boot = testing::boot_test::<AppContext, App>().await.unwrap();
let new_user: Result<users::Model, ModelError> = users::Model::create_with_password(
&boot.app_context.db,
&RegisterParams {
Expand Down Expand Up @@ -131,7 +131,7 @@ async fn can_find_user_roles() {
async fn cannot_find_user_before_conversation() {
configure_insta!();

let boot = testing::boot_test::<App>().await.unwrap();
let boot = testing::boot_test::<AppContext, App>().await.unwrap();
let new_user: Result<users::Model, ModelError> = users::Model::create_with_password(
&boot.app_context.db,
&RegisterParams {
Expand Down
Loading
Loading