mrpc/templates/typescript_client.rs.ts

44 lines
1.2 KiB
TypeScript

@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 @{
@for f in &s.fields { @f.name: @ty_to_str(&f.ty);
}@}
}
export class MRPCConnector @{
url: string;
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 = @{
service: '@s.name',
method: '@m.name',
data: @{@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),
onmessage: __e => __cbk(JSON.parse(__e.data))
@});} else {fetch(this.url, @{method: 'POST', body: JSON.stringify(__msg)@});}
@}
}}
@}