SakaDream / actix-web-rest-api-with-jwt

A simple CRUD backend app using Actix-web, Diesel and JWT
MIT License
523 stars 107 forks source link

How to make middleware support async fucntion call? #40

Open measproem opened 2 years ago

measproem commented 2 years ago

Your project very good skeleton of Actix Web rest API especially your Middleware jwt concept , I have changed to support other database library beside diesel , every thing work fine but I have one issue because of new database library need to working on async example token_utils::verify_token(&token_data, pool).await in file name auth_middleware.rs I hard to call it or how make it works in middleware. I hope get your help Thank you

FrostPrice commented 1 year ago

Hello. I was able to solve this middleware with async functions by doing the following:

Inside the Impl for the AuthenticationMiddleware<S> in the line where I need to make an async call to the DB, I used the executor::block_on() method, and created async block that will have the call of the async function with .await on it.

let my_awaited_return = executor::block_on( async {
      my_async_function(&variable).await
});

Depending on your necessity, you might need to move the values to the async block, like this:

let my_awaited_return = executor::block_on( async move {
      my_async_function(&moved_variable).await
});

This also worked with actix-web version 4

I hope it helps.

Best Regards.

measproem commented 1 year ago

Thank you