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 のインスタンスか、属性名をキーにしたハッシュ)。無ければ省略できます。
  • 戻り値は、S200 S404 ... のインスタンス(res.status res.body res.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
  )
end
wrappers/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
end
  • Comatype::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))
end
wrappers/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

型の対応#

  • string bool int は String true/false Integer。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)。
  • 制約(min max pattern)は、読むとき・送るときにランタイムが確かめます。