Ruby
Ruby 3.1 以上が必要です。ランタイム comatype(packages/ruby)は標準ライブラリだけで動きます(json・net/http・bigdecimal・socket など)。Ruby は動的な言語なので、生成物は「型の記述」を書き出し、変換と検証はランタイムが行います。
生成されるもの#
comatype_gen/
├─ types.rb 名前付きの型(Comatype::Model / Comatype::Enum のサブクラス) ComatypeGen::Types
├─ init.rb ラッパー・ctx・ラッパーのステータス ComatypeGen::Init
├─ user_put_id.rb エンドポイントごと ComatypeGen::UserPutId
└─ all.rb 全部を require するrequire_relative "comatype_gen/all" で読み込みます。
クライアント#
user_put_id.rb
require "comatype"
require_relative "comatype_gen/all"
UserPutId = ComatypeGen::UserPutId
def put_user(id, user)
# Arguments are params: search: headers: body: (a Model, or a hash keyed by attr). Types are validated from params / body of put__id.comat
res = Comatype::C.put(UserPutId::ENDPOINT, params: { id: id }, body: user)
case res
when UserPutId::S200 then res.body # UserData (res.headers is S200Headers)
when UserPutId::S404 then res.body # ApiError
end
end- 引数は
params:search:headers:body:(Model のインスタンスか、属性名をキーにしたハッシュ)。無ければ省略できます。 - 戻り値は、
S200S404... のインスタンス(res.statusres.bodyres.headers)。case/whenで絞り込めます。 .comatに無いステータスはComatype::UnexpectedStatusError、検証エラーはComatype::ValidationError(pathとreason)。- 通信は
Net::HTTP(同期)です。
init.rb
# Client init file: pass the implemented wrappers
# The base url defaults to baseUrl in init.comat. Override with the COMATYPE_BASE_URL environment variable or base_url:
# Call init_comatype once at startup (whether a wrapper is on or off is decided by defaults.comat and `wrap` in each .comat)
require "comatype"
require_relative "comatype_gen/all"
require_relative "wrappers/auth"
def init_comatype
Comatype::C.init(
# With the generated Init.wrappers, a missing wrapper declared in init.comat raises ArgumentError
wrappers: ComatypeGen::Init.wrappers(auth: AUTH),
# Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
cookies: true
)
endwrappers/auth.rb
# A wrapper is implemented as a lambda taking (req, nxt) (corresponds to the `wrapper auth` of init.comat)
AUTH = lambda do |req, nxt|
req.headers["Authorization"] = "Bearer #{ENV['API_TOKEN']}"
nxt.call(req)
endサーバ#
user_put_id.rb
require "comatype"
require_relative "comatype_gen/all"
UserPutId = ComatypeGen::UserPutId
def register_user_put_id(server)
server.put(UserPutId::ENDPOINT) do |req|
# req.params.id: String, req.body: UserData, req.ctx[:auth].user (wrap auth is on)
user = Db::User.update(req.params.id, req.body) # the app's own storage
next UserPutId::S404.new(ComatypeGen::Types::ApiError.new(code: "not_found", message: "user not found")) unless user
# headerRes (X-Resource-Version) of user/defaults.comat
UserPutId::S200.new(user, headers: { x_resource_version: "v2" })
end
endComatype::Sのインスタンスにブロックでハンドラを登録します。戻り値はS200.new(body, headers: {...})などのレスポンス。cookie は.with_cookie(value, max_age: 3600)/.clear_cookie。sは Rack 互換です(run s)。s.handle(method, target, headers, body)は任意のフレームワーク用の入口、s.serve(port: 3000)は標準ライブラリだけの簡易サーバです。
init.rb
# Server init file: pass the implemented wrappers. The cookie settings (name, httpOnly, etc.) are in init.comat
require "comatype"
require_relative "comatype_gen/all"
require_relative "wrappers/auth"
def init_comatype(server)
# With the generated Init.wrappers, a missing wrapper declared in init.comat raises ArgumentError
server.init(ComatypeGen::Init.wrappers(auth: AUTH))
endwrappers/auth.rb
# A wrapper is implemented as a lambda taking (req, nxt) (corresponds to the `wrapper auth` of init.comat)
require_relative "../comatype_gen/all"
AUTH = lambda do |req, nxt|
user = verify_session(req.cookie("session")) # the app's own logic
next ComatypeGen::Init.s401(ComatypeGen::Types::ApiError.new(code: "unauthorized", message: "login required")) unless user
# On endpoints with `wrap auth` on, a handler can read req.ctx[:auth].user
req.ctx[:auth] = ComatypeGen::Init::AuthCtx.new(user: user)
nxt.call(req)
end型の対応#
stringboolintはStringtrue/falseInteger。int64はInteger(通信上は文字列)。dateはDate、datetimeはTime、decimalはBigDecimal、urlはURI、bytesはString(バイナリ)、jsonはHash/Array。uuid系・email・phone・timeは、形式を検証したStringです(uuid は小文字にそろえます)。- 省略可能(
?)とT | nullはnilになれます。属性名は snake_case(X-Request-Id→x_request_id)。 - 制約(
minmaxpattern)は、読むとき・送るときにランタイムが確かめます。