Vapor 3 路由
Vapor 3 Routing
路由问题
我正在使用最新版本的 Vapor 并尝试学习它。
我正在尝试在控制器中创建路由。我已经在 routes.swift 文件中注册了控制器。我现在需要在控制器文件中正确注册路由。
我已经使用 RouteCollection 扩展了 class,并且正在为 post 请求编写路由。我打算传递一个 JSON 对象并有一个 class 从 Content 扩展而来,以便更容易地从 JSON 数据创建对象。
post 请求然后将数据提交到 FoundationDB 数据库。我硬编码时可以读写,但现在需要使用请求来发送数据。
这就是我的。
func boot(router: Router) throws {
router.post( ) { // need to send JSON data in the request to the createCountry function
}
func createCountry( ) { // I need to put the JSON data into a class called Country which has three string fields; country_name, Timezone and default_location. This will then be written to the foundationDB
}
router.post()应该如何格式化,createCountry()函数存根应该如何格式化?我一直在输入 req: Request 和 various -> 无济于事。我显然在根本上做错了。
我不知道我是否理解但是要注册路由然后处理请求你应该这样写:
class CountryController: RouteCollection {
// Register routes for country
func boot(router: Router) throws {
let group = router.grouped("api", "country")
group.post(Country.self, at: "new", use: newCountryHandler)
}
}
private extension CountryController {
func newCountryHandler(_ request: Request, newCountry: Country) throws -> Future<HTTPResponseStatus> {
// Handle your new Country object
}
}
路由问题
我正在使用最新版本的 Vapor 并尝试学习它。
我正在尝试在控制器中创建路由。我已经在 routes.swift 文件中注册了控制器。我现在需要在控制器文件中正确注册路由。
我已经使用 RouteCollection 扩展了 class,并且正在为 post 请求编写路由。我打算传递一个 JSON 对象并有一个 class 从 Content 扩展而来,以便更容易地从 JSON 数据创建对象。
post 请求然后将数据提交到 FoundationDB 数据库。我硬编码时可以读写,但现在需要使用请求来发送数据。
这就是我的。
func boot(router: Router) throws {
router.post( ) { // need to send JSON data in the request to the createCountry function
}
func createCountry( ) { // I need to put the JSON data into a class called Country which has three string fields; country_name, Timezone and default_location. This will then be written to the foundationDB
}
router.post()应该如何格式化,createCountry()函数存根应该如何格式化?我一直在输入 req: Request 和 various -> 无济于事。我显然在根本上做错了。
我不知道我是否理解但是要注册路由然后处理请求你应该这样写:
class CountryController: RouteCollection {
// Register routes for country
func boot(router: Router) throws {
let group = router.grouped("api", "country")
group.post(Country.self, at: "new", use: newCountryHandler)
}
}
private extension CountryController {
func newCountryHandler(_ request: Request, newCountry: Country) throws -> Future<HTTPResponseStatus> {
// Handle your new Country object
}
}