Parameters

Parameters are a registered type that can be initialized from a String.

They can be part of a Route, and be extracted from requests that are called in that route.

Creating custom parameters

To create a custom parameter type, simply conform to Parameter and implement the conversion function make and a unique slug.

In this example, the User class will be initialized from a parameter that represents its identifier.

We recommend prefixing custom Parameter identifiers.

  1. class User : Parameter {
  2. var username: String
  3. // The unique (prefixed) identifier for this type
  4. static var uniqueSlug = "my-app:user"
  5. // Creates a new user from the raw `parameter`
  6. static func make(for parameter: String, in request: Request) throws -> User {
  7. return User(named: parameter)
  8. }
  9. init(named username: String) {
  10. self.username = username
  11. }
  12. }

Using (custom) parameters

After conforming a type to Parameter you can access its static property parameter as part of a path.

  1. router.on(.get, to: "users", User.parameter, "profile") { request in
  2. let user = try request.parameter(User.self)
  3. // Return the user's Profile sync or async (depending on the router)
  4. }