-
Notifications
You must be signed in to change notification settings - Fork 0
/
wasm.go
62 lines (53 loc) · 1.36 KB
/
wasm.go
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
//go:build js
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"syscall/js"
"github.com/invopop/gobl.cli/internal"
)
func main() {
r, w := io.Pipe()
js.Global().Call("addEventListener", "message", js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
jsonEvent := js.Global().Get("JSON").Call("stringify", args[0].Get("data")).String()
if _, err := fmt.Fprintln(w, jsonEvent); err != nil {
fmt.Fprintln(os.Stderr, "failed to send event: %s", err)
}
return nil
}))
js.Global().Call("postMessage", map[string]any{"ready": true})
processMessages(r)
fmt.Println("exiting")
}
func processMessages(r io.Reader) {
bulkOpts := &internal.BulkOptions{
In: r,
}
for result := range internal.Bulk(context.TODO(), bulkOpts) {
postMessage(result)
}
}
func postMessage(result *internal.BulkResponse) {
response := js.Global().Get("Object").New()
if result.ReqID != "" {
response.Set("req_id", result.ReqID)
}
response.Set("seq_id", result.SeqID)
if len(result.Payload) > 0 {
response.Set("payload", string(result.Payload))
}
if result.Error != nil {
ed, err := json.Marshal(result.Error)
if err != nil {
response.Set("error", fmt.Sprintf("failed to marshal error: %s", err.Error()))
}
response.Set("error", string(ed))
}
if result.IsFinal {
response.Set("is_final", true)
}
js.Global().Call("postMessage", response)
}