marcj / angular2-localstorage

Angular 2+ decorator to save and restore variables/class properties to HTML5 LocalStorage automatically.
303 stars 107 forks source link

Implemented custom de/serialization #46

Closed sbbowers closed 8 years ago

sbbowers commented 8 years ago

This change provides support for complex datatypes that require a more complex serializer that JSON.stringify/parse

Decorator function signature now accepts named parameters via an object. Maintains backward compatibility with original function signature as well.

Example:

// Collection is just an array-like class I wrote
export class ModelStore extends Collection<BaseModel> {
    static serialize(collection: Collection<BaseModel>):string {
        return JSON.stringify(collection.slice());
    }

    static deserialize(serialized: string) {
        return new Collection<BaseModel>(JSON.parse(serialized).map((m:Object) => new BaseModel(m)));
    }
}

export class AppStore {
    @LocalStorage({serialize: ModelStore.serialize, deserialize: ModelStore.deserialize})
    private myData: ModelStore = new Collection<BaseModel>();
}
skie commented 8 years ago

Any reason this PR not merged yet? Looks super useful.

sbbowers commented 8 years ago

¯(ツ)/¯ In the interim, I'm doing something like the following. I keep all of my storage in a DataStore class that I inject into other classes that need it. DataStore is responsible for constructing real models on top of the generic objects provided by LocalStorage. For now, generic JSON.stringify is working for me for serialization. ModelStore has all the logic to do lookup/insert/delete, etc.

export type ConstructorFunc<T> = { new(...args : any[]): T; }

export class ModelStore<modelType extends BaseModel> {
    private data: Array<modelType> = [];

    constructor(data: Array<modelType>, modelType: ConstructorFunc<modelType>) {
        this.data = data;
        this.data.forEach((e, i, d) => { d[i] = new modelType(e) });
    }
}

export class DataStore {
    @LocalStorage() private myModels: Array<MyModel> = [];

    myModelStore: ModelStore<MyModel>;

    constructor() {
        this.myStore = new MyStore<MyModel>(this.myModels, MyModel);
    }
}```
marcj commented 8 years ago

This library is almost not maintained anymore, pls see readme. However, I'm merging this for now as its really useful. Thanks!