nathanbuchar / electron-settings

đź“ť A simple persistent user settings framework for Electron.
https://electron-settings.js.org
MIT License
817 stars 60 forks source link

Cannot use key with . (dot) in it #91

Closed Kineolyan closed 4 years ago

Kineolyan commented 7 years ago

Hello everyone,

I am trying electron settings to store projects by their git url. Unfortunately, the url - such as git@github.com - contains a ., so it is split as two parts of a key. Would it be possible to make a version of get/set/has/delete that takes an array instead of string ?

Cheers

nathanbuchar commented 7 years ago

Hmm, that certainly is an interesting problem…

My first suggestion would be to avoid using such a complex string as a JSON key, but I could add an option to all accessor/mutator methods named keyPath which is true by default. Setting this to false would mean interpreting the first parameter as a raw string rather than a keypath. Here's an example:

settings.set('git@github.com:nathanbuchar/electron-settings.git', 'value', { keyPath: false });

What do you think?

stavlocker commented 7 years ago

@nathanbuchar @Kineolyan I think that there's a cleaner solution, adding support for escaping characters so you could write \. in your code and it would treat it as a literal dot. (and \\ for literal backslash). It's already used in basically everything and it would feel natural.

Kineolyan commented 7 years ago

Hello @stavlocker, @nathanbuchar , I suggested an array of strings because it was the solution I saw in Moreartyjs to read data and more famously lodash. It seemed natural to me because it was eventually what the code does here. And it was still possible to edit a given value in nested maps.

Nothing prevents to also implement the solution escaping the . and \.

stavlocker commented 7 years ago

Agreed.

Kineolyan commented 7 years ago

I will try to submit a PR for this in the next day, if we are ok with the syntax.

Cheers

nathanbuchar commented 7 years ago

@Kineolyan Can you provide a code example of how this would potentially look like with electron-settings? Thanks :)

Kineolyan commented 7 years ago

Sure.

const settings = require('electron-settings');
settings.setAll({
  'git@github.com': {
     'electron-settings': {
       owner: '@nathanbuchar'
    }
  }
});

if (settings.has('git@github\\.com.electron-settings')) {
  // => true, as github.com is escaped
  console.log(
    'many thanks to',
    settings.get(['git@github.com', 'electron-settings', 'owner']));
}

Including both my suggestion and escaping requirement from @stavlocker.

Cheers

nathanbuchar commented 4 years ago

Electron Settings v4 was just released and supports key paths with dots in them! Under the hood, the Electron Settings accomplishes this by using a few of lodash collection methods. Just pass an array of keys, like so:

// given:
//
// {
//   "foo": {
//     "bar.baz": true
//   }
// }

await settings.get(['foo', 'bar.baz']);
// => true