CrudRouter 是一个受 Rails 启发的 Vapor 路由系统扩展,它可以尽可能简单地为任何 Model 设置 CRUD (创建、读取、更新、删除) 路由。CrudRouter 提供了一个与 Rails 的 resources 非常相似的 API,但增加了一些额外的功能,包括自动响应器生成和类型安全。
在您的 Package.swift 文件中
dependencies: [
.package(url: "https://github.com/twof/VaporCRUDRouter.git", from: "1.0.0")
]
和
targets: [
.target(name: "App", dependencies: ["CrudRouter"]),
]
在您的路由设置中 (默认 Vapor API 模板中的 routes.swift)
router.crud(register: Todo.self)
就是这样!
这一行代码为您提供了以下路由。
GET /todo // returns all Todos
GET /todo/:id // returns the Todo with :id
POST /todo // create new Todo with provided body
PUT /todo/:id // update Todo with :id
DELETE /todo/:id // delete Todo with :id
生成的路径默认使用小写蛇形命名法。例如,如果您这样做:
router.crud(register: SchoolTeacher.self)
您将获得像这样的路由:
GET /school_teacher
GET /school_teacher/:id
POST /school_teacher
PUT /school_teacher/:id
DELETE /school_teacher/:id
如果您想提供自己的路径,而不是使用提供的模型名称,您也可以这样做:
router.crud("account", register: User.self)
结果是:
GET /account
GET /account/:id
POST /account
PUT /account/:id
DELETE /account/:id
假设您有一个 User 模型,它是另一个模型 Todo 的父模型。如果您想公开属于特定 User 的所有 Todo 的路由,您可以这样做:
router.crud(register: User.self) { controller in
controller.crud(children: \.todos)
}
结果是:
GET /user
GET /user/:id
POST /user
PUT /user/:id
DELETE /user/:id
GET /user/:id/todo // returns all Todos belonging to the User with :id
GET /user/:id/todo/:id // returns the Todo with :id belonging to the User with :id
POST /user/:id/todo // creates a new Todo belonging to the User with :id
PUT /user/:id/todo/:id // updates the Todo with :id belonging to the User with :id
DELETE /user/:id/todo/:id // deletes the Todo with :id belonging to the User with :id
在提供的闭包中,您还可以公开相关 Parent 和 Sibling 的路由
controller.crud(children: \.todos)
controller.crud(parent: \.todos)
controller.crud(siblings: \.todos)
如果您想注册一个 Model,但您不希望每个路由都可用,您可以指定您想要的路由,或排除您不想要的路由。
router.crud(register: Todo.self, .except([.create, .delete])) { controller in
controller.crud(parent: \.owner, .only([.read]))
}
结果是:
PUT /todo/:id
GET /todo/:id
GET /todo
GET /todo/:id/tag/:id