Home > OS >  Using optional parameters in wasm building
Using optional parameters in wasm building

Time:11-16

I'm trying to convert the below code from IndexedDB JavaScript API into 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: "[email protected]" });
 }

So, I wrote:

    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: "[email protected]" }`)

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

But i got the below runtime error:

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.

I understand the reason is because of not including {keyPath: "id"} at result.Call("createObjectStore", "employee" to match the JavaScript one, but I tried the below and nothing worked:

// 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"}"`)

Any thought how to make it?

CodePudding user response:

Based on the documentation for ValueOf:

https://pkg.go.dev/syscall/[email protected]#ValueOf

This should work:

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