简体   繁体   English

Vapor 3:创建自定义服务器响应

[英]Vapor 3: Create Custom Server Response

I want to create a custom server response for my controllers and my errors.我想为我的控制器和我的错误创建一个自定义服务器响应。

Here is the model:这是 model:

struct ServerResponse<T: Content>: Content {
    let code: Int
    let message: String
    let data: T?
}

My create request:我的创建请求:

func create(_ req: Request) throws -> Future<ServerResponse<User>> {
        try req.content.decode(User.self).flatMap { user in
            user.save(on: req).map { user in
                ServerResponse(code: ?, message: ?, data: user)
            }
        }
    }

In case of success, how can I get the HTTPStatus code to add it to the Response?如果成功,如何获取HTTPStatus代码以将其添加到响应中?

And the message if success is OK , if the error is a custom description or the description of the HTTPStatus .如果成功是OK的消息,如果错误是自定义描述或HTTPStatus的描述。

The Content protocol conforms to a ResponseCodable protocol that in turn conforms to a ResponseEncodable protocol. Content协议符合ResponseCodable协议,而 ResponseCodable 协议又符合ResponseEncodable协议。 Vapor uses the ResponseEncodable protocol to convert a type to an EventLoopFuture<Response> that it can send to the client. Vapor 使用ResponseEncodable协议将类型转换为可以发送给客户端的EventLoopFuture<Response>

What you'll want to do is define a custom implementation of the encode(for:) method that ResponseEncodable requires.您要做的是定义ResponseEncodable所需的encode(for:)方法的自定义实现。 It will look something like this:它看起来像这样:

func encode(for request: Request) -> Future<Response> {
    do {
        let response = Response(status: HTTPResponseStatus(statusCode: self.code))
        try response.content.encode(self.data)
        return request.eventLoop.future(response)
    } catch let error {
        return request.eventLoop.future(error: error)
    }
}

I don't really know how you plan on using the message property, so I left that out.我真的不知道你打算如何使用message属性,所以我把它省略了。

As a side note, you probably only need to conform your custom type to ResponseEncodable instead of Content , but it won't make a big difference.作为旁注,您可能只需要使您的自定义类型符合ResponseEncodable而不是Content ,但这不会有很大的不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM