Is it possible to register app data in middleware's constructor?
Hello, I would like to register new app_data during the creation of middleware. Is there a way for doing this?
Let's say.
struct MyAppData {
//
}
impl MyAppData {
pub fn new<M: T1. A: T2>(arg1: M, arg2: A) -> Self {
// implementation
}
}
// wrap middleware and call MyAppData::new with arg1, arg2
// then register app data on `actix_web::App`
app.wrap(MyMiddleware::new(arg1, arg2))
IIRC, it should be possible to do this already. Middlewares get access to req and therefore the Extensions which can be added to.
@robjtede do you have a minimum code or reference for it? while checking the docs I cannot find it.
@robjtede do you have a minimum code or reference for it? while checking the docs I cannot find it.
req.app_data()
@zimingWu are you sure that it is not just a getter but also a setter?
@zimingWu are you sure that it is not just a getter but also a setter?
my mistake.
try req.extensions_mut().insert( your app data )?
register app data in middleware's constructor
I think it may help your mental model to say that app data is set on the HttpRequest as it passes through the service chain, not on App.
ServiceRequest::extensions_mut is the solution as pointed out by @zimingWu
@robjtede @zimingWu actually what I really need is to be able to register a global data only when construct/register the middleware then access it through req.app_data in every request.
It differs from extensions_mut because if I use extensions_mut then I'll need to construct my data for every request which is not ideal, it can be heavy
What I want is more a shared, global data to be constructed and registered to app while registering a middleware
Construct the data, store in the Middleware struct and add to extensions on requests.
cannot we avoid add to extensions on requests? can we make app_data also setter?
cannot we avoid
add to extensions on requests? can we makeapp_dataalso setter?
tell us what you want, instead of how you wish to implement. i think you might trying a wrong practice
@zimingWu I have been quite clear, register a global data during the construction of middleware.
IIRC, it should be possible to do this already. Middlewares get access to req and therefore the Extensions which can be added to.
If the middleware configuration is always the same, we do not need to save the same data for each request. If there are dependencies between middleware, we also need to consider the order of middleware.
so if I understand right; concretely, you want to have mutable access to App within Transform::new_transform?
Hi there, I was searching similar to thing that you guys proposed as solution. The thing that I want to achieve is storing authenticated user in the request app_data. By storing user, I would retrieve it from handler by using web::Datareq.extensions_mut().insert(user). I am not able to get it neither in handler nor in middleware. I can assure that Autheticate is called before Admin middleware. Do you have any suggestion over this design, or can identify the issue?
Hi there, I was searching similar to thing that you guys proposed as solution. The thing that I want to achieve is storing authenticated user in the request app_data. By storing user, I would retrieve it from handler by using web::Data. You may suggest using Guards, however, i also want to implement a new middleware called AdminUser, and it also needs already authenticated user. I dont want to check at every middleware for user authentication, that leads to storing user at AuthenticateMiddleware and use it at AdminUser middleware. However when i set user via
req.extensions_mut().insert(user). I am not able to get it neither in handler nor in middleware. I can assure that Autheticate is called before Admin middleware. Do you have any suggestion over this design, or can identify the issue?
impl<S, B> Service for YourAuthMiddleWare<S>
where
blablabla
{
fn call(&mut self, req: ServiceRequest) -> Self::Future {
req.extensions_mut().insert(User::new("name".to_string()));
blablabla()
}
}
pub struct User {
name: String,
}
impl User {
fn new(name: String) -> Self {
User { name: name }
}
}
async fn handler(req: HttpRequest) -> Result<HttpResponse> {
info!(
"{:?}",
req.head().extensions().get::<User>().expect("").name
);
blablabla()
}
does this help?
@zimingWu definitely works, thanks for the answer. I supposed to use the inserted data like calling req.app_data::<User>() in middleware or using typing in the handler like
async fn index(user: web::Data<User>) -> impl Responder {}
With your solution, since it returns a reference to data itself, I was only possible to use it like
if let Some(user) = req.head().extensions().get::<User>() {
/// Do your stuff
}
Otherwise I was getting creates a temporary which is freed while still in use error.
is there any way to manipulate app_data at anywhere in the runtime except specifying them at the App Factory construction. I would like to access user via typing in the handler if it is possible, which makes code much more cleaner.
Do you have any idea about handling diesel queries inside the middleware. Do they block the thread?
@zimingWu definitely works, thanks for the answer. I supposed to use the inserted data like calling
req.app_data::<User>()in middleware or using typing in the handler likeasync fn index(user: web::Data<User>) -> impl Responder {}With your solution, since it returns a reference to data itself, I was only possible to use it like
if let Some(user) = req.head().extensions().get::<User>() { /// Do your stuff }Otherwise I was getting creates a temporary which is freed while still in use error.
is there any way to manipulate app_data at anywhere in the runtime except specifying them at the App Factory construction. I would like to access user via typing in the handler if it is possible, which makes code much more cleaner.
Do you have any idea about handling diesel queries inside the middleware. Do they block the thread?
- no, you can't. you may find a way to work around with it, but i don't suggest. since, app_data is application data, not request data, it could be shared by multiple requests that in the same thread. If you insist, you might need to block the thread to make sure that user's infos wont be taint by other requests.
- i don't know. but it looks like a blocking api.
@zimingWu thanks for the answers. I will stick to requests extension.
This issue's namesake will likely never be possible with current architecture. Adding layers of data to a request is how all levels of the system work. Post-v3 release I will be experimenting with some alternate API features that will hopefull make this layered strategy more obvious and easy to work with.
@zimingWu definitely works, thanks for the answer. I supposed to use the inserted data like calling
req.app_data::<User>()in middleware or using typing in the handler likeasync fn index(user: web::Data<User>) -> impl Responder {}With your solution, since it returns a reference to data itself, I was only possible to use it like
if let Some(user) = req.head().extensions().get::<User>() { /// Do your stuff }Otherwise I was getting creates a temporary which is freed while still in use error.
I'm using this like so:
pub async fn index(schema: web::Data<AppSchema>, http_req: HttpRequest, gql_req: Request) -> Response {
let mut request = gql_req.into_inner();
if let Some(auth) = http_req.head().extensions().get::<BearerAuth>() {
request = request.data(auth);
}
schema.execute(request).await.into()
}
but it would still throw both E0597 and E0716.
Any ideas? I don't get exactly what's wrong and why. The cause of the problem seems to be the .head() call which seems to be impossible to get to work. :(