sindresorhus / electron-store

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc
MIT License
4.6k stars 150 forks source link

New Store object and config file mismatch #194

Open tmaffia opened 3 years ago

tmaffia commented 3 years ago

At application launch, after creating a new Store object with the schema as a parameter, the object is not immediately persisted to the config file. Is this expected behavior? It creates a disconnect between the store object and the file.

const _store = new Store({ schema });

Afterwords, if I explicitly set any key/value pair:

_store.set('key', 'value');

the library seems to write out the aforementioned schema defaults to the file, along with whatever I explicitly set. I've not configured the config.json file at all, it uses default name and Windows location. I can't find any functions that mention explicitly writing out to the config file in the docs. It does however say: "Changes are written to disk atomically, so if the process crashes during a write, it will not corrupt the existing config."

The problem I'm trying to solve is validation of config values on startup. If my config file is empty at startup, My validation is matching against the new Store object default values in memory, instead of the empty values in my file. I could fix this by explicitly looking through the file but I assume that's not the intended approach. Maybe new Store() is not appropriate in this situation?

coltoneshaw commented 2 years ago

@sindresorhus - I'm seeing this same behavior using a schema file with defaults. When i start with a fresh config.json file on electron startup it builds all the properties except the ones that are type: 'object' with additional properties defined underneath. The second I attempt to write to the object that doesn't exist it generates all the required properties based on their defaults.

Is best practice to include both a schema and the defaults to ensure everything is generated?

Electron-store v8.0.1

coltoneshaw commented 2 years ago

Scratch this. The second I posted I stumbled upon a comment from 2019 outlining a fix. Seems to work here. Can we get this moved to the docs? It would be hugely beneficial. I'm happy to stick in a PR with an object having defaults example if you'd like.