mrpc/templates/typescript_client.rs.ts

46 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

@use itertools::Itertools;
@use crate::data::RPC;
@use crate::generators::ts_c::*;
@(rpc: &RPC)
import @{ fetchEventSource @} from '@@microsoft/fetch-event-source';
@for e in &rpc.enums {
export enum @e.name @{
@for (k,v) in &e.values { @k = @v,
}@}
}
@for s in &rpc.structs {
export interface @s.name@get_struct_generics(s) @{
@for f in &s.fields { @f.name: @ty_to_str(&f.ty);
}@}
}
export class MRPCConnector @{
url: string;
private __create_msg(service: string, method: string, data: any) @{
return @{service, method, data@};
@}
public constructor(url: string) @{
this.url = url;
@}
@for s in &rpc.services { @for m in &s.methods {
public @(s.name)_@(m.name)(@method_args(m))@method_ret(m) @{
const __msg = this.__create_msg('@s.name', '@m.name', @{@m.args.iter().map(|a| &a.name).join(",")@});
@if m.ret.is_some() && !m.ret_stream {return fetch(this.url, @{
method: 'POST',
body: JSON.stringify(__msg)
@}).then((__r) => __r.json());}
else if m.ret_stream {fetchEventSource(this.url, @{
method: 'POST',
body: JSON.stringify(__msg),
2023-12-22 14:27:37 +00:00
onmessage: __e => __cbk(JSON.parse(__e.data)),
onerror: __e => @{throw __e;@},
onclose: () => __cbk(null)
@});} else {return fetch(this.url, @{method: 'POST', body: JSON.stringify(__msg)@}).then(__r => @{@});}
@}
}}
@}