Below is my current routes:
api/v1/users/login
api/v1/users/register
api/v1/users/forgot
And so on...
I want to know, how can I create all these routes keeping a single file auth.dart
let's say. So that I will be having all the code in single file related to authentications but the routes will remain as they are above mentioned.
Here's the current folder structure that is creating routes:
Dart Frog does not support having multiple routes in a single file, as it is a file-based routing framework.
What you can do however is setup the routes as you have in the screenshot, and define both a middleware and inject an AuthManager
:
// In your _middleware.dart
final _authManager = AuthManager();
Handler middleware(Handler handler) {
return handler
.use(provider<AuthManager>((_) => _authManager));
}
// In any of your routes
FutureOr<Response> onRequest(RequestContext context, String id) async {
final authManager = context.read<AuthManager>();
// Do something with authManager
}
If you want your AuthManager
to be per request, instead of using a global value you can construct it every time the create
, that is the method you pass to the provider, is called:
// In your _middleware.dart
Handler middleware(Handler handler) {
return handler.use(
provider<AuthManager>((context) {
// Do something with context
return AuthManager(...);
}),
);
}
See the docs about dependency injection for more information