Swift
Swift のランタイムは、Swift Package の Comatype(packages/swift)です。Foundation だけに依存します。macOS 12 / iOS 15 以上、Swift 5.9 以上。生成物は、ターゲット ComatypeGen(既定の出力先は Sources/ComatypeGen)として同じ package に置きます。
生成されるもの#
<out>/
├─ Types.swift 名前付きの型(struct・enum)
├─ Init.swift ComatypeInit: ラッパー・ctx・ラッパーのステータス
└─ UserPutId.swift エンドポイントごと(enum 名は PascalCase の連結名)swift
// Package.swift
dependencies: [.package(path: "/path/to/comatype/packages/swift")],
targets: [
.target(name: "ComatypeGen", dependencies: [.product(name: "Comatype", package: "swift")]),
]クライアント#
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
}
}- 引数は、
params/search/ ヘッダがあればRequest、bodyだけならボディそのもの、無ければNoArg()。任意のプロパティには既定値があります。 - 呼び出しは
async throws(URLSession)。戻り値のResponseは enum で、switchで絞り込めます(case .s200(let body, let headers))。 .comatに無いステータスはComatypeError.unexpectedStatus、検証エラーはValidationError(pathと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)
}サーバ#
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")))
}
}Sのインスタンスに、async のハンドラを登録します(ラッパーも async です)。ハンドラはS.Reply(.s200(body: ...))を返し、cookie は.withCookie(CookieValue("v", maxAge: 3600))。s.serve(host:port:)は POSIX ソケットの HTTP/1.1 サーバです(keep-alive、チャンク転送のボディ、読み取りのタイムアウトreadTimeout、ボディの上限maxBodySize、stop())。TLS は無いので、前段のプロキシで終端してください。await s.handle(method:target:headers:body:)は任意のフレームワーク用の入口です。
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)))
}型の対応#
uuiduuidv4uuidv7はUUID、datetimeはDate、decimalはDecimal、urlはURL、bytesはData、intはInt、int64はInt64(通信上は文字列)、jsonはJSON(ランタイムの enum)。datetimeは独自型LocalDate/LocalTime、emailphoneはEmail/Phone。- 省略可能(
?)とT | nullはOptional。enum はStringの raw value を持つ Swift の enum です。
注意#
- Swift のランタイムの単体テストは
swift run comatype-selftest(XCTest が無い環境でも動きます)。