Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mounting the router on a route group #33

Open
matthewcheok opened this issue Sep 9, 2024 · 1 comment
Open

Mounting the router on a route group #33

matthewcheok opened this issue Sep 9, 2024 · 1 comment

Comments

@matthewcheok
Copy link

matthewcheok commented Sep 9, 2024

Suppose we had some route configuration like:

func routes(_ app: Application) throws {
  let unprotectedAPI = app.grouped("api")

  let tokenProtectedAPI = unprotectedAPI
    .grouped(Token.authenticator())
    .grouped(UserModel.guardMiddleware())
  
  try tokenProtectedAPI
    .grouped("users")
    .register(collection: UserController())
}

How would we convert this to use a parser-backed router? This is generally useful for chaining on middlewares to specific route groups, i.e. if we wanted everything behind the api path to require token-based authentication.

@matthewcheok
Copy link
Author

I tried adding this extension:

extension RoutesBuilder {
  public func mount<R: Parser>(
    _ router: R,
    use closure: @escaping (Request, R.Output) async throws -> AsyncResponseEncodable
  ) where R.Input == URLRequestData {
    self.grouped(AsyncRoutingMiddleware(router: router, respond: closure))
  }
}

// routes.swift
tokenProtectedAPI.mount(apiRouter, use: apiHandler)

But it looks like unlike global middleware, route-specific middlewares are not even executed if the route group does not contain any routes.

@matthewcheok matthewcheok changed the title Mounting the router on RoutesBuilder Mounting the router on a route group Sep 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant