Skip to content

Macros for writing Controller (RouteCollection) #3210

Open
@Star-Lord-PHB

Description

Currently writing controllers in Vapor requires manually getting values from Request and implementing the boot(routes:) function . The handler functions are in the body of the Controller while the path and middleware definitions are in the boot(routes:) function. Maybe it is a good idea to use swift macro to automate some of these steps and put handler functions and their corresponding path and middleware together.

For example:

struct Controller: RouteCollection {
    func boot(routes: RoutesBuilder) throws {
        routes.on(.GET, "hello", ":firstName", "lastName", use: self.sayHello(req:))
    }
    func sayHello(req: Request) throws -> String {
        let firstName = try req.parameter.require("firstName", as: String.self)
        let lastName = try req.parameter.require("lastName", as: String.self)
        return "Hello \(firstName) \(lastName)"
    }
}

Can be written in something like:

@Controller
struct Controller {
    @EndPoint(method: .GET, path: "hello", ":firstName", ":lastName")
    func sayHello(firstName: String, lastName: String) -> String {
        return "Hello \(firstName) \(lastName)"
    }
}

Here is an initial implement this idea in this repo, please have a check

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions