用于 Vapor 框架的 Swift 包,可简化响应 DTO 和 JSON 结构

可连接套件

ConnectableKit 是 Vapor 框架的 Swift 包,它简化了 API 项目的响应 DTO 和 JSON 结构。

特征

  • 通用 JSON 结构:该协议允许您定义包装的 Vapor 结构。ConnectableContent
  • 为每个响应定制HTTPStatus。
  • 错误中间件配置,用于将 Vang 的错误作为 ConnectableKit JSON 输出进行处理。
  • CORSMiddleware配置,用于轻松处理Vapor的CORSMiddleware。

结构

类型 描述 类型
地位 五种可能的情况:信息、成功、重定向、失败和错误。 响应状态:字符串
消息 来自服务器的可选自定义消息。 字符串?= 无
数据 泛型关联类型,表示作为响应发送的数据。它可以是符合 Vapor 内容协议的任何类型,其中包括字符串、int 和自定义结构或类等类型。 连接?= 无

{
  "status": "success",
  "message": "Profile fetched successfully.",
  "data": {
    "id": "EBAD7AA7-A0AF-45F7-9D40-439C62FB26DD",
    "name": "Tuğcan",
    "surname": "ÖNBAŞ",
    "profileImage": "http://localhost:8080/default_profile_image.png",
    "profileCoverImage": "http://localhost:8080/default_profile_cover_image.png"
  }
}

安装

可以使用 Swift Package Manager 安装 ConnectableKit。只需将以下行添加到您的 Package.swift 文件中:

dependencies: [
    .package(url: "https://github.com/tugcanonbas/connectable-kit.git", from: "1.0.0")
]

dependencies: [
    .product(name: "ConnectableKit", package: "connectable-kit"),
],

Usage

To use the ConnectableKit Framework,

– For Connectable

In Struct, simply conform that is ProfileConnectable

import ConnectableKit

struct Profile: Model, Connectable {
    @ID(key: .id)
    var id: UUID

    @Field(key: "name")
    var name: String

    @Field(key: "surname")
    var surname: String

    @Field(key: "profileImage")
    var profileImage: String

    @Field(key: "profileCoverImage")
    var profileCoverImage: String
}

In Response call for responding wrapped generic response..DTO

return .toDTO(_ httpStatus: Vapor.HTTPStatus = .ok, status: ResponserStatus = .success, message: String? = nil) -> Responser<Self>

app.get("/profiles", ":id") { req -> Profile.DTO in
    let id = try req.parameters.require("id", as: UUID.self)
    let profile = try await Profile.query(on: req.db).filter(\.$id == id).first()!

    return profile.toDTO(message: "Profile fetched successfully.")
}

app.post("/profiles") { req -> Profile.DTO in
    let profile = Profile(
        id: UUID(),
        name: "Tuğcan",
        surname: "ÖNBAŞ",
        profileImage: "http://localhost:8080/default_profile_image.png",
        profileCoverImage: "http://localhost:8080/default_profile_cover_image.png"
    )
    try await profile.save(on: req.db)

    return profile.toDTO(.created, message: "Profile fetched successfully.")
}

– For Empty Response

app.put("/profiles", ":id") { req -> Connector.DTO in
    let id = try req.parameters.require("id", as: UUID.self)
    let update = try req.content.decode(Profile.Update.self)

    let profile = try await Profile.query(on: req.db).filter(\.$id == id).first()!
    profile.name = update.name
    try await profile.save(on: req.db)

    return Connector.toDTO(.accepted, message: "Profile updated successfully.")
}

{
  "status": "success",
  "message": "Profile updated successfully."
}

Connectable protocol

public protocol Connectable: Content {
    associatedtype DTO = Responser<Self>
    func toDTO(_ httpStatus: Vapor.HTTPStatus, status: ResponserStatus, message: String?) -> Responser<Self>
}

public extension Connectable {
    func toDTO(_ httpStatus: Vapor.HTTPStatus = .ok, status: ResponserStatus = .success, message: String? = nil) -> Responser<Self> {
        let response = Responser(httpStatus, status: status, message: message, data: self)
        return response
    }
}

– For ErrorMiddleware

import ConnectableKit
ConnectableKit.configureErrorMiddleware(app)

Error Response Example

Database Error:

{
  "status": "error",
  "message": "server: duplicate key value violates unique constraint \"uq:users.username\" (_bt_check_unique)"
}

AbortError:

guard let profile = try await Profile.query(on: req.db).filter(\.$id == id).first() else {
    throw Abort(.notFound, reason: "User not found in our Database")
}

Response

{
  "status": "failure",
  "message": "User not found in our Database"
}

If you use , don’t forget to use before all middleware configureations.ConnectableKitErrorMiddleware

See in Vapor’s Documentation Error Middleware

– For CORSMiddleware

import ConnectableKit
ConnectableKit.configureCors(app)

func configureCORS

public static func configureCORS(_ app: Vapor.Application, configuration: Vapor.CORSMiddleware.Configuration? = nil)

Inspiration

The JSend specification, developed by Omniti Labs, outlines a consistent JSON response format for API endpoints. I found the specification to be very helpful in ensuring that API consumers can easily understand and parse the responses returned by the API.

As a result, I have heavily borrowed from the JSend specification for the response format used in this project. Specifically, I have adopted the status field to indicate the overall success or failure of the request, as well as the use of a message field to provide additional context for the response.

While I have made some modifications to the response format to suit the specific needs of this project, I am grateful for the clear and thoughtful guidance provided by the JSend specification.


License

ConnectableKit is available under the MIT license. See the LICENSE file for more info.


GitHub

点击跳转