dexie / Dexie.js

A Minimalistic Wrapper for IndexedDB
https://dexie.org
Apache License 2.0
11.58k stars 642 forks source link

writing to private singletons from REST api #2084

Open dusty-phillips opened 4 days ago

dusty-phillips commented 4 days ago

I have a preferences table that is indexed with private singletons. I can get this table by accessing this path:

const encodedSettingsId = encodeURIComponent(`#settings:${userId}`)
const path = `/all/preferences/${encodedSettingsId}`

The id of the returned object looks like this:

    "#settings:8IzD5unb5idu0dcTeQcZRUYF"

However, I can't for the life of me figure out how to write a value back to this entity. I'm doing a POST to /all/preferences with an object that has the same id:

{
    "id": "#settings:8IzD5unb5idu0dcTeQcZRUYF",
    "realmId": "8IzD5unb5idu0dcTeQcZRUYF",
    "displayName": "foo",
       // other values
}

I get a 200 response. But the changed values do not get stored to the db.

I checked dexie-cloud export and it doesn't seem to be creating an unexpected object with a different id. It just seems to be accepting my POST and ignoring the contents. Am I formatting something incorrectly or is writing to private keys intentionally or accidentally not supported?

Note: Leaving realmId off the posted object results in a 400 error.

dfahlander commented 4 days ago

Thanks, I'll look into it

dusty-phillips commented 1 day ago

@dfahlander, No pressure, but do you think it will be a quick fix or should I look for a workaround that uses non-singleton keys?

dfahlander commented 1 day ago

Thanks for reminder. Is the realmId a userId or an id of a real Realm object?

dfahlander commented 1 day ago

Oh, here's the reason: Private singletons must have a timestamp property called '$ts' on them or else they won't be saved. All properties starting with '$' are also escaped to start with double $ ('$$'). So basically, POST the object as:

{
    "id": "#settings:8IzD5unb5idu0dcTeQcZRUYF",
    "realmId": "8IzD5unb5idu0dcTeQcZRUYF",
    "displayName": "foo",
       // other values
        "$$ts": Date.now()
}

I suppose this might be missing in the docs. Dexie cloud addon will do that when using put() but not using add(). It's a way to enable table.add(privateSingleton) to only be added ever once, while table.put(privateSingleton) will replace existing.

dusty-phillips commented 12 hours ago

That solves it, thanks! I think it is indeed missing in the docs; I did look.

dfahlander commented 12 hours ago

Thanks! I should update the docs.