Giter Club home page Giter Club logo

ember-local-storage's People

Contributors

bekzod avatar bncoelho avatar charlesfries avatar cibernox avatar cvx avatar davewasmer avatar eharrow avatar ember-tomster avatar fsmanuel avatar greenkeeperio-bot avatar jasonmit avatar julienmelissas avatar kepek avatar knownasilya avatar koopa avatar miguelcobain avatar mikek2252 avatar mwpastore avatar offirgolan avatar ramblurr avatar rwjblue avatar selvaa89 avatar selvarajantonyraj avatar sukima avatar wozny1989 avatar wuron avatar xcambar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ember-local-storage's Issues

desc.get is not a function TypeError: desc.get is not a function

When using virtual property, you wil get this error

import StorageObject from 'ember-local-storage/local/object';

export default StorageObject.extend({
  storageKey: 'client-intake',
  initialContent: {

    step1Valid: function() {
      return false;
    }.property(),
  }
});

Updating two controllers

I'm not sure whether the issue I'm dealing with is related to this addon, or plain ember practice, anyway:

I'm using the addon on two controllers (Application and a specific one called Employee) and is used to manage and display specific settings:

From the Employee controller one can save an employee-ID into localStorage. You can see your actions 'live' at the related template when setting and unsetting this employee.

The application template displays the name of your chosen employee (through a service), but doesn't change 'live' when the Employee controller sets / unsets an employee...

Here's my code:
/controllers/application.js

import Ember from 'ember';
import Settings from 'my-app/models/settings';

export default Ember.Controller.extend({
    settings         : Settings.create(),
    myContact        : null,
    myContactService : Ember.inject.service('my-contact'),
    myContactUpdater : Ember.observer('settings.myContact_employeeID', function() {
        var self = this;
        this.get('myContactService').retrieve()
        .then(function(employee){
            self.set('myContact', employee);
        });
    }),

    init: function () {
        this.myContactUpdater();
    }
});

/controllers/employees/single.js

import Ember from 'ember';

export default Ember.Controller.extend({

    // myContactService: Ember.inject.service('my-contact'),
    application: Ember.inject.controller('application'),

    settings: Ember.computed.alias('application.settings'),

    isMyContact: function() {
        return this.model.id == this.get('settings.myContact_employeeID');
    }.property('settings.myContact_employeeID', 'this.model.id'),



    actions: {
        'setMyContact': function (employee_id) {
            this.set('settings.myContact_employeeID', employee_id);
        },
        'removeMyContact': function () {
            this.set('settings.myContact_employeeID', null);
        }
    }

});

services/my-contact.js

import Ember from 'ember';
import Settings from 'my-app/models/settings';

export default Ember.Service.extend({

    store : Ember.inject.service(),
    settings: Settings.create(),

    /**
     * Returns a Promise
     */
    retrieve: function() {
        var employee_id = this.get('settings.myContact_employeeID');
        if( employee_id ) {
            // return promise
            // for fetchById
            // on Employee model
            return this.get('store').fetchById('employee', employee_id);
        }
        else{
            // return promise
            // with Null param
            return new Ember.RSVP.Promise(function(resolve, reject) {
                resolve(null);
            });
        }
    }
});

How to use in multiple controllers?

Hi! I've run into a problem using the local-storage modal I created with this in multiple locations. I suppose that when using create() it creates a new object instance for every controller it is used in โ€“ if I change the content in one controller now, how can I get these changes in another one?

I'm trying to make a history of objects the user viewed. The detail page will add an entry to the local storage object, which should be displayed on the start page.

Changes on object in array are not saved

Hi, it's me again :)

I'm not sure if that's by purpose or if there is still a bug. At least it reminds me on #17.

My scenario is that I have an array of objects which will change from time to time.
It is important that the item stays at the original index why I can't just remove and add id again.

items is an array and look like:

[
   {id: 1, count: 3}, 
   {id: 2, count: 5}
]

Use case as follows:

items.arrayContentWillChange();

var item = items.objectAt(1);
item.count = 9;

items.arrayContentDidChange();

I have to trigger arrayContentDidChange so that the observers can react on the change and rerender the updated count value.

So when having this setup the value of the Array does change, but NOT the item in local storage.

storageFor

Implement storageFor helper

  • deprecate initialContent use _initialContent internal
  • Readme
  • Tests
  • support legacy keys
  • blueprints

Dynamic property in the initialContent object

Hi, I use a i18n package for ember and I specified the default value for locale in env.js file.

Now I want to store the current language in localStorage, but I want to avoid copy-paste for the default value and keep it only in env.js. Something like this:

initialContent: {
   locale: %default_value%
}

I can't use this.get('i18n.defaultLocale') (a usual way) for that, since it's an array declaration and this cannot be used on high-level. Ember.computed works but it stores the whole Ember object.

How can I set a dynamic value in this case?

Records not retrieved from store with namespaced model

Hi,

when using a namespaced model (e.g. blog/post), records can be persisted but not retrieved from the store. This is because everything behind a '/' is interpreted as an id which fails for namespaced model names.

The workaround we used is to change how the payload key and path name are derived from the model name in the serializer and adapter, respectively.

// app/adapters/blog/post.js
import Adapter from 'ember-local-storage/adapters/adapter';

export default Adapter.extend({
  pathForType(modelName) {
    return this._super(modelName.replace('/', '::'));
  },
});
// app/serializers/blog/post.js
import Serializer from 'ember-local-storage/serializers/serializer';

export default Serializer.extend({
  modelNameFromPayloadKey(key) {
    return this._super(key.replace('::', '/'));
  },

  payloadKeyFromModelName(modelName) {
    return this._super(modelName).replace('/', '::');
  },
});

Can't get a record from the local storage

I can't seem to get at the record I have saved in local storage with findRecord

I have a route that requires someone to authenticate with my backend using a key, that calls a normal ajax action that I take the response and store in local storage using the default local storage adapter

Ember.$.ajax({
type: 'get',
dataType: 'json',
url: `http://***/api/users/url/${params.short_url}?key=${ENV.APP.api_key}`
}).then((response)=>{
var user = this.store.createRecord('user',response);
user.set('id',1);
user.save().then(()=>{
    this.transitionTo('index');
    });
});

Then I'm attempting to make another ajax call in another route using the user_id property of that saved user in local storage like so

var user = this.store.findRecord('user',1).get('user-name');

Maybe I'm just doing this wrong but when I console.log that it comes as undefined. How do I get the user out of local storage to grab a specific property from it?

Strange behaviour on IE11

Hi,

I'm using the plugin to store a couple of simple values in local storage and it works all fine, except in IE (IE11), where there is no initial value set, and on changing (is a page size that I can change in an input) it gets in an infinite loop setting the variable to the new and initial value back and forth.

ember-data dependency

I am using ember-local-storage in a project that's not using ember-data.
Since 0.0.7 is now failing at runtime ("DS is not defined").
In 0.0.9, build is also failing with an obscure error ('Invalid Version: undefined') when ember-data is not present.

Is the strict dependency on ember-data a long term requirement, or is just a temporary accident?

Editing an object in an array

Say you have an array of objects. How can I edit one of those objects given the index? I've tried this:

this.get('stuff').objectAt(1).set('sport', 'hockey');

I get an error that says set is not a function.

restoring array of objects from local storage and pushMany to memory storage

I was trying to restore array of objects from local storage and pushMany to memory storage when application is ready. It seems that the object in the array does not include id, due to which i was not able do so. Would it be possible to include id for each object while pushing to local storage? Or is there some solution to this kind of cases?

Having trouble using in a service

I'm attempting to use a service to access data from the local storage since I'll be saving a json object with user info. But I can't seem to get it to work.

In my service I am attempting to set a property for the users id like so

import Ember from 'ember';
import LocalUser from 'bidr/models/user-local';

export default Ember.Service.extend({
    localUser: LocalUser.create(),
    user_id: this.get('localUser').get('content').user.id
});

But in my component where I am attempting to access this property I am getting this.get is not a function in the console as an error.

Is there some other setup I need to do instead to get this to work in the service?

Inject local storage model to be used anywhere

This may be outside the scope of this addon but I am using the adapter and serializer to store user info in local storage. This gets populated with normal ajax requests that create and save records into the local storage store.

What I need is to be able to use this user record in local storage (there will only ever be one at a time) in computed properties and to display in templates.

I'm just not sure on what approach I need to take. Most importantly it needs to notify computes and observables that properties on the user record have changed so they can recompute etc. Seems obvious but I was previously using local storage as a custom service but updating the local storage object did not notify computes of property changes.

Expose a function to retrieve the storage if available

The function returns null in case there is no storage or the storage itself.

  • tryStorage(type) # will return null or the nativeStorage
  • getStorage(type, fallback = {})
    • type 'session'
    • type 'local'
    • fallback is optional and can be a polyfill
  • add an initializer that sets the polyfill

Cannot set values on deep neested properties

Hi everybody,

I've a object that looks this:

{
  details: {
    address: {
      first: {...},
      second: {...}
    }
  }
}

It is easily possible to set values on the first level (eg. details.address), but there's no chance to change values on a deeper level (eg. details.address.first).

Ember recognizes the change an show the right value, if I render the output on my template. But the local storage item shows no change.

Any suggestions to solve this issue?

sessionStorage adapter/serializer?

Thanks for the awesome library!

I found myself wanting to use sessionStorage for ember models rather then localStorage. I'm wondering what you'd think about supporting an adapter/serializer for sessionStorage in the library? Or, just making the existing adapter a little more flexible for accommodating the change to sessionStorage.

Below is what I had to do to make my own extension of the existing adapter (the serializer required no changes). As you can see I'm overriding some internal properties of the class, which makes me a little leery as the library internals could change at any time.

I'm happy to provide a pull request for either if you're interested.

import Ember from 'ember';
const {
  get,
} = Ember;

import LocalStorageAdapter from 'ember-local-storage/adapters/adapter';
import { getStorage } from 'ember-local-storage/helpers/storage';
import StorageArray from 'ember-local-storage/session/array';

export default LocalStorageAdapter.extend({
    _storage: getStorage('session'),

    _getIndex(type) {
        const indices = get(this, '_indices');

        if (!indices[type]) {
            indices[type] = StorageArray
            .extend({ _storageKey: 'index-' + type })
            .create();
        }

        return indices[type];
    },
});

Could not find module `ember-local-storage/adapters/local`

Hi,

I'm trying to configure "ember-local-storage" to work with "ember-data" and I can not make it work, maybe I'm not getting your explanations on the Readme.

Could you provide some more information on how is "ember-local-storage" interacting with "ember-data"??
Is it like if I'm already using "ember-data" and then I integrate "ember-local-storage" then the model goes automatically to localStorage??
I have done this two instructions from you:

If you already use Ember Data for non LocalStorage models you can use a per type adapter and serializer.

// app/adapters/post.js
export { default } from 'ember-local-storage/adapters/local';
// or export { default } from 'ember-local-storage/adapters/session';

// app/serializers/post.js
export { default } from 'ember-local-storage/serializers/serializer';

and have got the error:

Uncaught Error: Could not find module `ember-local-storage/adapters/local` imported from ...

What I want to accomplish is that, I have a few JSON objects that I give as a model to a template and I want to load those JSON objects in localStorage and connect that with "ember-data".

Thanks in advance for the help,
Best.

Package doesn't follow semver

Moving from 0.0.6 to 0.0.7/8 introduced Ember-Data 1.13.5 and breaking changes to this library for apps that cannot support the sweeping upgrade pains of the newer E-D versions. The latest versions should have at least been 0.1.0, and moving forward it would be nice to have semver followed so we avoid these nasty surprises. :)

Add a JSON object to the storageObject

How would I go about adding a JSON object to the local storage using the storageObject?

When I try adding it like I normally would make a JSON object it's all empty.

Or is this not how local storage is intended to be used?

Ember-data dependency

It seems the project depends on Ember-data (addon/adapters/base.js imports DS). It would be wonderful if Ember Data was an optional dependency.

Thanks for open sourcing your lib, it works like a charm!

DS Adapter

  • README
    • application adapter import
    • application serializer import
    • initializer for store.importData()/store.exportData()

Named exports

import { Adapter, Serializer, storageFor } from 'ember-local-storage';
  • Adapter
  • Serializer
  • storageFor

Using adapter and tests

Please describe best ways to work with adapter while tests. How to mock/clear store on each test etc. If I miss something in documentation - link be enough. Thx

reset method

It might make sense to add a reset() method to StorageObject that basically does this.setProperties(this.initialContent);.

What do you think?

How to get started using local storage? Any compelte examples?

Does anyone have a simple example where I can understand how the routes - components - storage adapter is connected?

I created a "user" model, a "profile" route and I get a 404 in the console that "localhost:4200/users" cant be found.

Code is here: https://github.com/Levino/steuertools/tree/1268f966131f19c26f215dcfd137c55d549c2474

I just want localhost:4200/profile to render...

I know this is very basic, but the guides are so bad that I am close to throwing the towel with emberjs, so please someone help me out.

addObject storing null values

When i try to add new object on click without refreshing page in localstorage then its storing the existing value and setting null for the other data exiting in that, and when i repeat this after refreshing the page its working properly.

Querying on boolean attributes doesn't work when they are false.

The LS Adapter doesn't support querying on boolean model attributes when the values are false:

From adapter.js:217

        // Attributes
        if (key === 'id' || key === 'type') {
          recordValue = data[key];
        } else {
          key = serializer.keyForAttribute(key);
          recordValue = data.attributes ? data.attributes[key] : null;
        }

        if (recordValue) { // <----------------- this is the problem line
          return this._matches(recordValue, queryValue);
        }

If the model has an attribute like isAwesome: DS.attr('boolean', {defaultValue: false}),

Then a query like store.query('my-model', { filter: {isAwesome: false } }) returns 0 results.

storing to local-storage with addObjects becomes very slow when records grow

I was trying to store to local storage (around 500 records) and realised that the storing process is really slow (around 15 seconds). Here is my use case.

var records = this.store.peekAll(modelName).map(function (record) {

    return { id: record.id, content: record } ;

});

this.get('arrayOfRecords').addObjects(records);

However, when i use

this.get('arrayOfRecords').addObject(records);

The storing process completed in a second but updating to local storage did not work anymore.
Any idea how we can accomplish this?
Also, it would be nice to have some method to replace initial content.

Add new method destroy()

In addition to the reset method I think it would be cool to be able to completely remove the data from the storage by calling destroy() or something.

Discussion: Local Forage, moving beyond LS

Hey @fsmanuel

We've been using this addon in production for about a year now and we're hitting the limits of LocalStorage. Some of our users are hitting the 5MB size limit, and nearly all of them are affected by the slow performance of LS when there are many little reads and writes.

Our deployment target are devices as a hybrid app, and we have to support a range of devices that have varying abysmal support for WebSQL and IndexedDB. So I've been keen on migrating to an abstraction library such as Mozilla's LocalForage. https://mozilla.github.io/localForage/

LocalForage is an abstraction layer on top of LS, WebSQL, IndexedDB, and even Cordova SQLite. It provides a sync and async getItem/setItem API.

There's an existing ember-localforage-adapter project, however its implementation is rudimentary and not particularly performant. see: genkgo/ember-localforage-adapter#43

I would really like to migrate ember-local-storage to use the localforage API to get the benefit of increased storage options. The question is how to implement it, should it go directly into the project or become a fork?

Do you have any thoughts on this?

Edit: Hit save before I was finished.

Feature Request: restore nested ember object.

It would be great if the addon had the ability to restore full-blown ember objects that it has as properties. For instance an object that has nested sub objects of a different type. Right now it can restore nested objects but the objects restored are POJOs and because of that property changes on them cannot be observed/triggered.

Would it be as simple as storing an object type key along with it and then using the type key to instantiate a new version of the object and feeding it the POJO of the values?

I don't know if this falls under the category of an adapter or can be worked in with the object/array functionality that this addon provides.

queryRecord returns `undefined` when no result is found.. triggers Ember Assertion

in adapter.js in the queryRecord method, there exists this code:

      return records.then(function (result) {
        return { data: result.data[0] };
      });

Now, if there was no result found records is a {data: Array[0]} and result.data[0] returns undefined.

Later Ember asserts with the error:

Assertion Failed: normalizeResponse must return a valid JSON API document:
* data must be null, an object, or an array

(from here)

queryRecord should return null instead of undefined

Querying on camelCase poperties

Not sure if this is a bug or just an incorrect way of doing things.

In my model I define a property like so fooBar = DS.attr(). Later when I want to query against it I write store.query('my-model', {filter: { fooBar: value } }

Result: it never works, I always receive an empty list.

Debugging the adapter I see now that it is expecting the dasherized property, foo-bar to be passed as the query. This is strange and inconvenient as everywhere else I refer to it via myModel.get('fooBar').

Thoughts? Is this a bug?

Adapter Querying

I've just started using this addon for localstorage and it seems to work great however it looks as though querying has not been implemented. Is this correct? Is there a way to get it to work?

To be clear what I am trying to achieve is

this.store.query('myModel', {
   userId: '123'
})

However it is returning all models for that type.

Thanks,
Matt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.