【问题标题】:Vapor 3 Routing蒸汽 3 路由
【发布时间】:2018-07-27 16:00:47
【问题描述】:

路由问题

我正在使用最新版本的 Vapor 并尝试学习它。

我正在尝试在控制器中创建路由。我已经在 routes.swift 文件中注册了控制器。我现在需要在控制器文件中正确注册路由。

我已经使用 RouteCollection 扩展了该类,并且正在为发布请求编写一个路由。我打算传递一个 JSON 对象并拥有一个从 Content 扩展的类,以便更轻松地从 JSON 数据创建对象。

然后发布请求将数据提交到 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 和各种 -> 无济于事。我显然在根本上做错了什么。

【问题讨论】:

    标签: swift vapor


    【解决方案1】:

    我不知道我是否理解但要注册路由然后处理请求你应该这样写:

    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
        }
    
    }
    

    【讨论】:

    • 这看起来比我尝试的要好。创建的 Future 让我很难过,但 HTTPResponeStatus 看起来不错。谢谢
    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-17
    相关资源
    最近更新 更多