C#
The C# runtime is the NuGet package Comatype (packages/csharp). It has no external dependencies (JSON is our own, the client is System.Net.Http.HttpClient, and the server is System.Net.HttpListener). It needs .NET 8 or later (records, pattern matching and nullable reference types). The generated code is in the namespace ComatypeGen by default (set the target's package to change it) and is compiled with the nullable context turned on.
What is generated#
<out>/ default is ComatypeGen
├─ Types.cs Named types (records and enums), in the static class Types
├─ Init.cs Wrappers, ctx and wrapper statuses, in the static class Init
└─ UserPutId.cs One per endpoint (the static class name is a PascalCase joined name)Add the generated directory to your project and the package to its references:
shell
dotnet add package ComatypeClient#
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;
}
}
}- Calls are
async(C.GetAsync,PostAsync,PutAsync,PatchAsync,DeleteAsync,OptionsAsync,QueryAsync,HeadAsync) and returnTask<Response>. - The argument is
Requestif there areparams/search/ headers, the body itself if there is only abody, andNoArg.Instanceif there is neither. Responseis an abstract record with one sealed record per status (S200,S404, ...), which you narrow withswitchoris.- A status that is not in the
.comatisComatypeException.UnexpectedStatus, and a validation error isValidationException(PathandReason).
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);
};
}Server#
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" });
}
);
}
}- Register handlers on an instance of
S(s.Put(Endpoint, req => ...)). A handler can be synchronous orasync. For an endpoint withcookie onit returnsS.Reply<Response>(S.Reply<Response>.Of(res).WithCookie(CookieValue.Of(v).WithMaxAge(3600))); a plainResponseconverts to it. s.Serve("127.0.0.1", 3000)runs onHttpListener(port0picks a free port, and the returnedServerhasPortandStop()). It has no TLS, so terminate TLS at a proxy in front.await s.HandleAsync(method, target, headers, body)is the entry point you can call from any framework.
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;
}Type mapping#
uuiduuidv4uuidv7areGuid(the version is validated),dateisDateOnly,timeisTimeOnly,datetimeisDateTimeOffset(in UTC),decimalisdecimal(up to 28 digits),urlisUri,bytesisbyte[], andjsonisobject?(the parsed tree).emailandphoneareComatype.Email/Comatype.Phone(records).intandint64arelong.int64is a string on the wire.- Optional (
?) andT | nullareT?. Every record can be copied withwith(Search.Empty() with { Limit = 10 }), and hasEmpty()if everything is optional. - An enum is a C#
enumwhose members carry[WireName("...")]; a union of string literals is astringthat is validated. - Arrays are
List<T>.
Notes#
- Generated records and enums are named in PascalCase (
xResourceVersionbecomesXResourceVersion). A field whose name would clash with its record (or withValidate,Encode,Decode,Empty) gets a trailing_.