@@ -63,12 +63,32 @@ Middleware _modelValidationAndProviderMiddleware() {
6363// Main middleware exported for the /api/v1/data route group.
6464Handler middleware (Handler handler) {
6565 // This 'handler' is the actual route handler from index.dart or [id].dart.
66- // The .use() method applies middleware in an "onion-skin" fashion.
67- // The last .use() is the outermost layer.
68- // So, requireAuthentication() runs first. If it passes,
69- // _modelValidationAndProviderMiddleware() runs next.
70- // If that passes, the actual route handler is executed.
66+ //
67+ // The .use() method applies middleware in an "onion-skin" fashion, where
68+ // the last .use() call in the chain represents the outermost middleware layer.
69+ // Therefore, the execution order for an incoming request is:
70+ //
71+ // 1. `requireAuthentication()`:
72+ // - This runs first. It relies on `authenticationProvider()` (from the
73+ // parent `/api/v1/_middleware.dart`) having already attempted to
74+ // authenticate the user and provide `User?` into the context.
75+ // - If `User` is null (no valid authentication), `requireAuthentication()`
76+ // throws an `UnauthorizedException`, and the request is aborted (usually
77+ // resulting in a 401 response via the global `errorHandler`).
78+ // - If `User` is present, the request proceeds to the next middleware.
79+ //
80+ // 2. `_modelValidationAndProviderMiddleware()`:
81+ // - This runs if `requireAuthentication()` passes.
82+ // - It validates the `?model=` query parameter and provides the
83+ // `ModelConfig` and `modelName` into the context.
84+ // - If model validation fails, it returns a 400 Bad Request response directly.
85+ // - If successful, it calls the next handler in the chain.
86+ //
87+ // 3. Actual Route Handler (from `index.dart` or `[id].dart`):
88+ // - This runs last, only if both preceding middlewares pass. It will have
89+ // access to a non-null `User`, `ModelConfig`, and `modelName` from the context.
90+ //
7191 return handler
72- .use (_modelValidationAndProviderMiddleware ())
73- .use (requireAuthentication ());
92+ .use (_modelValidationAndProviderMiddleware ()) // Applied second (inner)
93+ .use (requireAuthentication ()); // Applied first (outermost)
7494}
0 commit comments