Swift

The Swift runtime is the Swift Package Comatype (packages/swift). It depends only on Foundation. It needs macOS 12 / iOS 15 or later and Swift 5.9 or later. Put the generated code in the same package as the target ComatypeGen (the default output is Sources/ComatypeGen).

What is generated#

<out>/
├─ Types.swift               Named types (structs and enums)
├─ Init.swift                ComatypeInit: wrappers, ctx and wrapper statuses
└─ UserPutId.swift           One per endpoint (the enum name is a PascalCase joined name)
swift
// Package.swift
dependencies: [.package(path: "/path/to/comatype/packages/swift")],
targets: [
    .target(name: "ComatypeGen", dependencies: [.product(name: "Comatype", package: "swift")]),
]

Client#

user_put_id.swift
import Comatype
import ComatypeGen
import Foundation

func putUser(id: UUID, user: UserData) async throws {
    // Request has params / headers / body, typed from the params block of put__id.comat
    let res = try await C.put(UserPutId.endpoint, UserPutId.Request(params: .init(id: id), body: user))

    switch res {
    case .s200(let data, _): _ = data   // UserData (the second is S200Headers)
    case .s404(let error, _): _ = error // ApiError
    default: break
    }
}
  • The argument is Request if there are params / search / headers, the body itself if there is only a body, and NoArg() if there is neither. Optional properties have defaults.
  • Calls are async throws (URLSession). The returned Response is an enum, which you narrow with switch (case .s200(let body, let headers)).
  • A status that is not in the .comat is ComatypeError.unexpectedStatus, and a validation error is ValidationError (path and reason).
init.swift
// Client init file: pass the implemented ComatypeWrap
// The base url defaults to baseUrl in init.comat. Override with the COMATYPE_BASE_URL environment variable or Config.baseURL
// Call initComatype() once at startup (whether a wrapper is on or off is decided by defaults.comat and `wrap` in each .comat)
import Comatype
import ComatypeGen

func initComatype() {
    C.initialize(C.Config(
        // With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
        wrappers: ComatypeInit.Wrappers(auth: auth),
        // Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
        cookieJar: CookieJar()
    ))
}
wrappers/auth.swift
// Implement a wrapper as a C.ComatypeWrap value (corresponds to the `wrapper auth` of init.comat)
import Comatype
import Foundation

let auth: C.ComatypeWrap = { req, next in
    var r = req
    r.headers.set("Authorization", "Bearer \(ProcessInfo.processInfo.environment["API_TOKEN"] ?? "")")
    return try await next(r)
}

Server#

user_put_id.swift
import Comatype
import ComatypeGen

func registerUserPutId(_ s: S) {
    s.put(UserPutId.endpoint) { req in
        // req.params.id: UUID, req.body: UserData, req.ctx.auth.user (wrap auth is on)
        guard let user = db.user.update(req.params.id, req.body) else { // the app's own storage
            return S.Reply(.s404(body: ApiError(code: "not_found", message: "user not found")))
        }
        // headerRes (X-Resource-Version) of user/defaults.comat
        return S.Reply(.s200(body: user, headers: UserPutId.S200Headers(xResourceVersion: "v2")))
    }
}
  • Register async handlers on an instance of S (wrappers are async too). A handler returns S.Reply(.s200(body: ...)), and cookies use .withCookie(CookieValue("v", maxAge: 3600)).
  • s.serve(host:port:) is an HTTP/1.1 server on POSIX sockets (keep-alive, chunked bodies, the read timeout readTimeout, the body limit maxBodySize, and stop()). It has no TLS, so terminate TLS at a proxy in front. await s.handle(method:target:headers:body:) is the entry point for any framework.
init.swift
// Server init file: pass the implemented ComatypeWrap
// The cookie settings (name, httpOnly, etc.) are in init.comat
import Comatype
import ComatypeGen

func initComatype(_ s: S) {
    // With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
    s.initialize(wrappers: ComatypeInit.Wrappers(auth: auth))
}
wrappers/auth.swift
// Implement a wrapper as an S.ComatypeWrap<AuthCtx> value (corresponds to the `wrapper auth` of init.comat)
import Comatype
import ComatypeGen

let auth: S.ComatypeWrap<ComatypeInit.AuthCtx> = { req, next in
    guard let user = verifySession(req.cookie("session")) else { // the app's own logic
        return ComatypeInit.s401(ApiError(code: "unauthorized", message: "login required"))
    }
    // On endpoints with `wrap auth` on, a handler can read req.ctx.auth.user, typed
    return try await next(req.withCtx(ComatypeInit.AuthCtx(user: user)))
}

Type mapping#

  • uuid uuidv4 uuidv7 are UUID, datetime is Date, decimal is Decimal, url is URL, bytes is Data, int is Int, int64 is Int64 (a string on the wire), and json is JSON (an enum in the runtime).
  • date and time are the own types LocalDate / LocalTime, and email and phone are Email / Phone.
  • Optional (?) and T | null are Optional. An enum is a Swift enum with a String raw value.

Notes#

  • The unit tests of the Swift runtime run with swift run comatype-selftest (they work even where XCTest is not available).