Rust
Rust のランタイムは、クレート comatype(packages/rust)です。serde / serde_json(JSON)、regex(形式と pattern の検証)、ureq(HTTP クライアント、同期)に依存します。
生成されるもの#
<out>/ 既定は src/comatype_gen
├─ mod.rs 各モジュールの宣言
├─ types.rs 名前付きの型(構造体・enum。serde の derive 付き)
├─ init.rs ラッパー・ctx・ラッパーのステータス
└─ user_put_id.rs エンドポイントごと(モジュール名は snake_case の連結名)main.rs に mod comatype_gen; を書くと使えます。生成された .rs は、手元に rustfmt があれば整形されます。
クライアント#
user_put_id.rs
// Call PUT /user/:id. Use the generated ENDPOINT and Request / Response
use crate::comatype_gen::types::UserData;
use crate::comatype_gen::user_put_id::{self, Request, Response};
use comatype::c;
pub fn put_user(id: &str, user: UserData) -> comatype::Result<()> {
// Request has params / headers / body, typed from the params block of put__id.comat
let res = c::put(
&user_put_id::ENDPOINT,
Request { params: user_put_id::Params { id: id.into() }, body: user, ..Default::default() },
)?;
match res {
Response::S200(data, _headers) => drop(data), // UserData, headers are S200Headers
Response::S404(error, _) => drop(error), // ApiError
_ => {}
}
Ok(())
}- 引数は、
params/search/ ヘッダがあればRequest(Defaultを実装しているので..Default::default()が使えます)、bodyだけならボディそのもの、無ければcomatype::NoArg。 - 戻り値は
Result<Response, comatype::Error>。Responseは enum で、バリアントはS200(body, headers)のように、ボディとヘッダがあるものだけを持ちます。 .comatに無いステータスはError::UnexpectedStatus、検証エラーはError::Validation(pathとreason)。- クライアントは同期(ureq)です。
init.rs
// Client init: pass the implemented ComatypeWrap
// The base url defaults to baseUrl in init.comat. Override with the COMATYPE_BASE_URL environment variable or Config.base_url
use crate::comatype_gen::init::Wrappers;
use comatype::c::{self, Config};
use comatype::CookieJar;
use std::sync::Arc;
pub fn init_comatype() {
c::init(Config {
// Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
cookie_jar: Some(Arc::new(CookieJar::new())),
// With the generated Wrappers, a missing wrapper declared in init.comat is a compile error
..Config::default().wrappers(Wrappers { auth: crate::auth::auth() })
});
}サーバ#
user_put_id.rs
// Handler for PUT /user/:id. Register the generated ENDPOINT with the Server
use crate::comatype_gen::types::ApiError;
use crate::comatype_gen::user_put_id::{self, Reply, Response, S200Headers};
use comatype::s::Server;
pub fn register(server: &Server, db: crate::db::Db) {
server.put(&user_put_id::ENDPOINT, move |req| -> Reply {
// req.params.id: Uuidv4, req.body: UserData, req.ctx.auth.user (wrap auth is on)
let Some(user) = db.update(&req.params.id.0, req.body) else {
return Response::S404(ApiError { code: "not_found".into(), message: "user not found".into() }, Default::default()).into();
};
// headerRes (X-Resource-Version) of user/defaults.comat
let headers = S200Headers { x_resource_version: Some("v2".into()), ..Default::default() };
Response::S200(user, headers).into()
});
}s::Serverにハンドラを登録します。ハンドラはFn(Request) -> Response。cookie onのエンドポイントではReply(Responseに.into()、cookie は.with_cookie(CookieValue::new(v).max_age(3600))/.clear_cookie())。server.handle(method, target, headers, body)は任意のフレームワークから呼べる入口です。server.serve("127.0.0.1:3000", |addr| ...)は標準ライブラリだけの簡易サーバ(接続ごとにスレッド)。- ハンドラの panic は
500(原因はon_errorに渡る)。
init.rs
// Server init: pass the implemented ComatypeWrap. The cookie settings (name, httpOnly, etc.) are in init.comat
use crate::comatype_gen::init::Wrappers;
use comatype::s::Server;
pub fn init_comatype(server: &Server) {
// With the generated Wrappers, a missing wrapper declared in init.comat, or a wrong type, is a compile error
server.init(Wrappers { auth: crate::auth::auth() });
}auth.rs
// Implement a wrapper as a ComatypeWrap<AuthCtx> value (corresponds to the `wrapper auth` of init.comat)
use crate::comatype_gen::init::{s401, AuthCtx};
use crate::comatype_gen::types::ApiError;
use comatype::s::ComatypeWrap;
pub fn auth() -> ComatypeWrap<AuthCtx> {
ComatypeWrap::new(|req, next| {
// On endpoints with `wrap auth` on, a handler can read req.ctx.auth.user, typed
let Some(user) = crate::verify_session(req.cookie("session")) else {
return s401(ApiError { code: "unauthorized".into(), message: "login required".into() });
};
next(req.with_ctx(AuthCtx { user }))
})
}型の対応#
emailphoneuuiduuidv4uuidv7datetimedatetimedecimalurlは、文字列を包んだ独自型(comatype::Emailなど)。.into()/::new()で作り、validateで形式を確かめます。intはi64、int64はcomatype::Int64(通信上は文字列)、bytesはcomatype::Bytes(base64)、jsonはserde_json::Value。- 省略可能(
?)とT | nullはOption<T>。フィールド名は snake_case(serde(rename)で元の名前に戻します)。 - 制約(
minmaxpattern)は、生成されたValidateの実装が確かめます。
注意#
- ユニオン型は、
T | nullと文字列リテラルだけのユニオンに対応しています。再帰する型(自分自身を含む型)は未対応です。 - ラッパーが足りないことは、
Wrappers構造体のフィールドが必須なので、コンパイル時に分かります。