在 wasm 构建中使用可选参数

Using optional parameters in wasm building

我正在尝试将以下代码从 IndexedDB JavaScript API 转换为 GO WASM:

request.onupgradeneeded = function(event) {
    var result = event.target.result;
    var objectStore = result.createObjectStore("employee", {keyPath: "id"});
    
       objectStore.add({ id: "00-01", name: "Karam", age: 19, email: "kenny@planet.org" });
 }

所以,我写道:

    var dbUpgrade js.Func
    var result, request js.Value

    dbUpgrade = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
        defer dbUpgrade.Release()
        result = this.Get("result")

        var objectStore = result.Call("createObjectStore", "employee")
        objectStore.Call("add", `{ id: "00-01", name: "Karam", age: 19, email: "kenny@planet.org" }`)

        window.Call("alert", "First record posted.")
        return nil
    })
    request.Set("onupgradeneeded", dbUpgrade)

但是我遇到了以下运行时错误:

panic: JavaScript error: Failed to execute 'add' on 'IDBObjectStore': The object store uses out-of-line keys and has no key generator and the key parameter was not provided.

我明白原因是因为 result.Call("createObjectStore", "employee" 没有包含 {keyPath: "id"} 来匹配 JavaScript,但我尝试了下面的方法但没有任何效果:

// 1.
result.Call("createObjectStore", "employee", "{keyPath: `id`}")
// 2.
key, _ := json.Marshal(map[string]string{"keyPath": "id"})
result.Call("createObjectStore", "employee", key)
// 3. 
result.Call("createObjectStore", `"employee", "{keyPath: "id"}"`)

想过怎么做吗?

基于 ValueOf 的文档:

https://pkg.go.dev/syscall/js@go1.17.3#ValueOf

这应该有效:

result.Call(...,map[string]interface{}{"keyPath": "id"})