-
Notifications
You must be signed in to change notification settings - Fork 10
/
client.go.tmpl
77 lines (69 loc) · 2.32 KB
/
client.go.tmpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
{{define "client"}}
{{- $typeMap := .TypeMap -}}
{{- $opts := .Opts -}}
{{- if .Services}}
//
// Client
//
{{- range .Services}}
export class {{.Name}} implements {{.Name}} {
protected hostname: string
protected fetch: Fetch
protected path = '/rpc/{{.Name}}/'
constructor(hostname: string, fetch: Fetch) {
this.hostname = hostname.replace(/\/*$/, '')
this.fetch = (input: RequestInfo, init?: RequestInit) => fetch(input, init)
}
private url(name: string): string {
return this.hostname + this.path + name
}
{{range $_, $method := .Methods}}
{{firstLetterToLower .Name}} = ({{template "methodInputs" dict "Method" . "TypeMap" $typeMap}}): {{if $method.StreamOutput}}WebrpcStreamController{{else}}Promise<{{$method.Name}}Return>{{end}} => {
{{- if $method.StreamOutput }}
const abortController = new AbortController();
const abortSignal = abortController.signal
if (options.signal) {
abortSignal.addEventListener("abort", () => abortController.abort(options.signal?.reason), {
signal: options.signal,
});
}
const _fetch = () => this.fetch(this.url('{{.Name}}'),
{{- if .Inputs | len }}createHTTPRequest(args, options.headers, abortSignal){{- else}}createHTTPRequest({}, options.headers, options.signal){{end }}
).then(async (res) => {
await sseResponse(res, options, _fetch);
}, (error) => {
options.onError(error, _fetch);
});
const resp = _fetch();
return {
abort: abortController.abort.bind(abortController),
closed: resp
};
}
{{- else }}
return this.fetch(
this.url('{{.Name}}'),
{{ if .Inputs | len }}createHTTPRequest(args, headers, signal)).then((res) => { {{- else }}createHTTPRequest({}, headers, signal)
).then((res) => { {{- end }}
return buildResponse(res).then(_data => {
{{ if .Outputs | len -}}
return {
{{- range $i, $output := .Outputs }}
{{$output.Name}}: <{{template "type" dict "Type" $output.Type "TypeMap" $typeMap}}>(_data.{{$output.Name}}),
{{- end }}
}
{{- else }}return {}{{- end }}
})
}, (error) => {
throw WebrpcRequestFailedError.new({ cause: `fetch(): ${error.message || ''}` })
})
}
{{end -}}
{{end}}
}
{{- end -}}
{{end -}}
{{if $opts.streaming}}
{{template "sse"}}
{{end}}
{{- end -}}