# Middleware

Middleware runs your code around a router's filters and handlers. Outer middleware runs once per update, before
anything in the router; inner middleware runs around each handler that matched. Both get a `Next` to pass the update
on.

## Example

An admin guard that stops the update for everyone else, and times the handler:

```no_run
use vaegram::handlers::{Next, UpdateContext};
use vaegram::prelude::*;

/// Provided to the handlers behind the guard.
#[derive(Clone)]
struct Admin(i64);

async fn ban(msg: Message, Dep(admin): Dep<Admin>) -> Result<()> {
    msg.reply(format!("Banned on behalf of {}.", admin.0)).await?;
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let app = Client::builder("guard_bot", 12345, std::env::var("API_HASH").unwrap())
        .bot_token(std::env::var("BOT_TOKEN").unwrap())
        .start()
        .await?;

    let mut admin = Router::new();
    admin.outer_middleware(|mut ctx: UpdateContext, next: Next| async move {
        match ctx.user_id() {
            Some(id) if id == 42 => {
                ctx.provide(Admin(id));
                next.run(ctx).await
            }
            // Returning without `next.run` keeps the update: later routes in this group don't see it.
            _ => Ok(()),
        }
    });
    admin.inner_middleware(|ctx: UpdateContext, next: Next| async move {
        let started = std::time::Instant::now();
        let result = next.run(ctx).await;
        eprintln!("handled in {:?}", started.elapsed());
        result
    });
    admin.message().handle(filters::command("ban"), ban);

    app.include_router(admin);
    app.run().await
}
```

## How it works

### Outer middleware

`router.outer_middleware(f)` runs on every update that reaches the router, for the kinds it has handlers for;
`router.message().outer_middleware(f)` adds one for a single kind, and makes the router take part in that kind even
without a handler. What the middleware does with `Next` decides who sees the update
(`src/handlers/router.rs:68-80`):

1. `next.run(ctx).await` hands it to the router's filters and handlers and gives back their result.
2. Returning without running `next` keeps the update: the routes after this router in its group never get it.
3. Running `next` and having nothing match passes the update on unchanged: the routes after this router in its group
   get it as it arrived, without this middleware's `provide` or `event_mut` changes.

### Inner middleware

`router.inner_middleware(f)` wraps each handler of the router and of the routers inside it whose filter matched,
after the outer middleware. Returning without `next.run` skips just that handler, which still takes its group's turn.
A parent's inner middleware runs outside its children's (`src/handlers/router.rs:82-86`). The built-in
`chat_action` is one:

```rust
# use vaegram::enums::ChatAction;
# use vaegram::handlers::{Router, chat_action};
# let mut router = Router::new();
router.inner_middleware(chat_action(ChatAction::Typing));
```

### The context

`UpdateContext` carries the event, the client and the values provided so far:

- `client()`, `kind()`, `chat_id()`, `user_id()`;
- `event::<T>()`, `event_mut::<T>()`, and the shortcuts `message()` and `callback_query()`;
- `data()`, `provide(value)` for handlers after this middleware (taken as `Dep<V>`).

`ctx.provide` replaces a value of the same type; `event_mut` changes stay inside the router when nothing matches.

### Order

Filters decide before the update is parsed where they can, so a router whose filters miss costs nothing. Then the
outer middleware in the order it was added (the first outermost, a parent's before its children's), the inner
middleware around the matched handler, and the handler. An `Err` from any of them goes to the router's `on_error`,
and one that reaches the client stops the later groups for that update.

## Common mistakes

- Ending an outer middleware with `Ok(())` while wanting the update to continue: that is the "keep" outcome. Call
  `next.run(ctx).await` and return its result.
- Changing `ctx` and expecting later routers to see it when nothing matched: they get the update as it arrived.
- Using outer middleware for per-handler work: it runs even when no handler matches. Use inner middleware.
- Dropping the result of `next.run`: errors stop at the middleware, and `on_error` never sees them.
- Adding middleware to a router that is never included: it never runs.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/handlers/index.html) for `Next`, `UpdateContext` and `chat_action`.
- [Routers](/docs/routers.md).
- [Filters](/docs/filters.md).
- [Errors](/docs/errors.md).