C#
C# のランタイムは、NuGet のパッケージ Comatype(packages/csharp)です。外部への依存はありません(JSON は独自実装、クライアントは System.Net.Http.HttpClient、サーバは System.Net.HttpListener)。.NET 8 以上が必要です(record・パターンマッチ・null 許容参照型)。生成物は、既定では名前空間 ComatypeGen に入ります(ターゲットの package で変えられます)。nullable コンテキストを有効にしてコンパイルされます。
生成されるもの#
<out>/ 既定は ComatypeGen
├─ Types.cs 名前付きの型(record・enum)。static クラス Types の中
├─ Init.cs ラッパー・ctx・ラッパーのステータス。static クラス Init の中
└─ UserPutId.cs エンドポイントごと(static クラス名は PascalCase の連結名)生成したディレクトリをプロジェクトに入れ、パッケージを参照に足します。
shell
dotnet add package Comatypeクライアント#
UserPutId.cs
using Comatype;
using ComatypeGen;
public static class UserPutIdSample
{
public static async Task PutUser(Guid id, Types.UserData user)
{
// Request has params / headers / body, typed from the params block of put_[id].comat
UserPutId.Response res = await C.PutAsync(
UserPutId.Endpoint,
new UserPutId.Request(new UserPutId.Params(id), UserPutId.RequestHeaders.Empty(), user)
);
switch (res)
{
case UserPutId.S200 ok:
Types.UserData data = ok.Body; // ok.Headers is S200Headers
break;
case UserPutId.S404 notFound:
Types.ApiError error = notFound.Body;
break;
}
}
}- 呼び出しは
asyncです(C.GetAsync、PostAsync、PutAsync、PatchAsync、DeleteAsync、OptionsAsync、QueryAsync、HeadAsync)。戻り値はTask<Response>です。 - 引数は、
params/search/ ヘッダがあればRequest、bodyだけならボディそのもの、無ければNoArg.Instance。 Responseは abstract record で、ステータスごとの sealed な record(S200、S404...)があります。switchやisで絞り込めます。.comatに無いステータスはComatypeException.UnexpectedStatus、検証エラーはValidationException(PathとReason)。
Init.cs
// 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.Run() once at startup (whether a wrapper is on or off is decided by defaults.comat and `wrap` in each .comat)
using Comatype;
using ComatypeGen;
public static class InitComatype
{
public static void Run()
{
C.Init(
new C.Config()
// With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
.WithWrappers(new Init.Wrappers(Auth.Wrap))
// Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
.WithCookieJar(new CookieJar())
);
}
}Wrappers/Auth.cs
// Implement a wrapper as a C.ComatypeWrap value (corresponds to the `wrapper auth` of init.comat)
using Comatype;
public static class Auth
{
public static readonly C.ComatypeWrap Wrap = (req, next) =>
{
req.Headers.Set("Authorization", "Bearer " + Environment.GetEnvironmentVariable("API_TOKEN"));
return next(req);
};
}サーバ#
UserPutId.cs
using Comatype;
using ComatypeGen;
public static class UserPutIdHandler
{
public static void Register(S s)
{
s.Put(
UserPutId.Endpoint,
req =>
{
// req.Params.Id: Guid, req.Body: Types.UserData, req.Ctx.Auth.User (wrap auth is on)
Types.UserData? user = Db.User.Update(req.Params.Id, req.Body); // the app's own storage
if (user == null)
return new UserPutId.S404(new Types.ApiError("not_found", "user not found"), UserPutId.S404Headers.Empty());
// headerRes (X-Resource-Version) of user/defaults.comat
return new UserPutId.S200(user, UserPutId.S200Headers.Empty() with { XResourceVersion = "v2" });
}
);
}
}Sのインスタンスに、ハンドラを登録します(s.Put(Endpoint, req => ...))。ハンドラは同期でもasyncでも書けます。cookie onのエンドポイントではS.Reply<Response>を返し(S.Reply<Response>.Of(res).WithCookie(CookieValue.Of(v).WithMaxAge(3600)))、ただのResponseはそのまま変換されます。s.Serve("127.0.0.1", 3000)はHttpListenerで動きます(ポート0で空いているポートを選び、戻り値のServerにPortとStop()があります)。TLS は無いので、前段のプロキシで終端してください。await s.HandleAsync(method, target, headers, body)は任意のフレームワークから呼べる入口です。
Init.cs
// Server init file: pass the implemented ComatypeWrap
// The cookie settings (name, httpOnly, etc.) are in init.comat
using Comatype;
using ComatypeGen;
public static class InitComatype
{
public static void Run(S s)
{
// With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
s.Init(new Init.Wrappers(Auth.Wrap));
}
}Wrappers/Auth.cs
// Implement a wrapper as an S.ComatypeWrap<AuthCtx> value (corresponds to the `wrapper auth` of init.comat)
using Comatype;
using ComatypeGen;
public static class Auth
{
public static readonly S.ComatypeWrap<Init.AuthCtx> Wrap = (req, next) =>
{
Types.UserData? user = VerifySession(req.Cookie("session")); // the app's own logic
if (user == null)
return Task.FromResult(Init.S401(new Types.ApiError("unauthorized", "login required")));
// On endpoints with `wrap auth` on, a handler can read req.Ctx.Auth.User, typed
return next(req.WithCtx(new Init.AuthCtx(user)));
};
private static Types.UserData? VerifySession(string? token) => null;
}型の対応#
uuiduuidv4uuidv7はGuid(バージョンも検証)、dateはDateOnly、timeはTimeOnly、datetimeはDateTimeOffset(UTC)、decimalはdecimal(28 桁まで)、urlはUri、bytesはbyte[]、jsonはobject?(パースした木)。emailphoneはComatype.Email/Comatype.Phone(record)。intとint64はlong。int64は通信上は文字列です。- 省略可能(
?)とT | nullはT?。record はwithでコピーでき(Search.Empty() with { Limit = 10 })、全部が省略可能ならEmpty()があります。 - enum は、メンバーに
[WireName("...")]が付いた C# のenum。文字列リテラルのユニオンは、検証付きのstringです。 - 配列は
List<T>です。
注意#
- 生成される record と enum は PascalCase の名前です(
xResourceVersionはXResourceVersion)。record 自身の名前やValidate/Encode/Decode/Emptyと衝突するフィールド名には、末尾に_が付きます。