funkensturm / ember-local-storage

The addon provides a storageFor computed property that returns a proxy and persists the changes to localStorage or sessionStorage. It ships with an ember-data adapter.
https://www.funkensturm.com/ember-local-storage/
MIT License
218 stars 76 forks source link

Allow dynamic prefix and suffix on storageFor. #313

Closed phcoliveira closed 5 years ago

phcoliveira commented 5 years ago

Hello there, great library by the way.

So I need to keep things in local storage individually; nothing sensitive, but they need to be personal. This is what I am using:

  // An instance of StorageObject
  allUsersFavorites: storageFor('my-addon/favorites'),

  setStorageForUser(user) {
    const id = user.get('id');
    const allUsersFavorites = this.get('allUsersFavorites');

    if (!isArray(allUsersFavorites.get(id))) {
      allUsersFavorites.set(id, []);
    }

    defineProperty(this, 'favorites', alias(`allUsersFavorites.${id}`));
  }

This works but it is not so great, as I have to use notifyPropertyChange after changing favorites.

Using a prefix on config is useful for general purposes, but what happens if an addon wants to define its own prefix? Will it change the host app's prefix?

To me, the prefix is not actually a big deal because I namespace the storage with a folder my-addon.

But what I really want is to have suffix. Given a storage named favorites, I would like to use storageFor as such:

setStorageForUser(user) {
  // id = 123
  const id = user.get('id');
  // This way, favorites could be a StorageArray instead of StorageObject
  defineProperty(
    this,
    'favorites',
    storageFor('favorites', { preffix: 'my-addon', suffix: id }
  );
}

And I expect the storage to be defined as:

key -> my-addon:favorites:123
value -> [] // StorageArray

Thanks!

fsmanuel commented 5 years ago

Hey @phcoliveira, thanks for the feedback. I think what you want is already possible. The storageFor accepts a second argument that should be a dependent key. So for your example that should work:

EmberObject.extend({
  user: EmberObject.extend({
    modelName: 'user',
    id: '123'
  }),
  favorites: storageFor('favorites', 'user')`
  // => 'storage:favorites:user:123'
})

The prefix is something I'll have to think about it.

phcoliveira commented 5 years ago

Thanks, Manuel.

I have read the docs about that dependent key, but I thought it was about serializing the whole object to be used by Ember Data again.

Kind regards.

fsmanuel commented 5 years ago

@phcoliveira if you have time to clarify the docs with an example that would be great.

phcoliveira commented 5 years ago

Sure thing, I will do it in the next couple of days.