carson-katri / router

Type-safe routing in SwiftUI
23 stars 0 forks source link

Path translation? #2

Open j-f1 opened 4 years ago

j-f1 commented 4 years ago

The standard for names in Swift is camelCase, but most websites use kebab-case for URL components. I see three different ways to reconcile this:

  1. Stick to camelCase URLs. This means the URLs are likely case sensitive and it would be obvious from the URL that this was not a regular web app.
  2. Automatically translate the route names to kebab-case. This would provide standard web app behavior.
  3. Allow users to somehow specify custom path components for a given route, overriding the default.

I think a combination of 2 and 3 would be best, providing sensible defaults while allowing users to potentially port existing URLs over to Tokamak, but I’m willing to have my mind changed!

carson-katri commented 4 years ago

Great point. What do you think about doing something like CodingKey?

enum AppRoutes: Routes {
  case firstRoute
  case secondRoute(arg: Int)

  enum RoutingKeys: String, RoutingKey {
    case firstRoute = "first-route"
    case secondRoute = "second-route"
  }
}
carson-katri commented 4 years ago

And maybe a RouteEncodingStrategy for common ones:

enum AppRoutes: Routes {
  static let encodingStrategy = .snakeCase
  // Or
  static let encodingStrategy = SnakeCaseRouteEncodingStrategy()

  case firstRoute
  case secondRoute(arg: Int)
}
j-f1 commented 4 years ago

How about a combination of the two?

enum AppRoutes: Routes {
  static let encodingStrategy = .snakeCase
  // Or
  static let encodingStrategy = Routes.Strategy { route in
    switch route {
      case firstRoute: return "first_route"
      case secondRoute: return "second_route"
    }
  }

  case firstRoute
  case secondRoute(arg: Int)
}
carson-katri commented 4 years ago

Ok, I got something implemented in abe322a & fa4374f:

enum AppRoutes: Routes {
  static let codingStrategy = KebabCaseRouteCodingStrategy()
  ...
}

A custom RouteCodingStrategy could be made as well:

struct CustomRouteCodingStrategy: RouteCodingStrategy {
  init() {}
  public func encode(_ components: [String]) -> String {
    // Join with a separator or do something fancier.
  }
}

Default is CamelCaseRouteCodingStrategy and enum cases are expected to be camelCase. We could probably check if they are snake_case/PascalCase though.