2016-08-26 17:37:59 +03:00
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
|
|
2016-10-14 20:10:08 +03:00
|
|
|
export type InternalStateType = {
|
2016-09-19 16:51:05 +03:00
|
|
|
[key: string]: any
|
|
|
|
|
};
|
|
|
|
|
|
2016-08-26 17:37:59 +03:00
|
|
|
@Injectable()
|
|
|
|
|
export class AppState {
|
2016-10-14 20:10:08 +03:00
|
|
|
_state: InternalStateType = {};
|
2016-08-26 17:37:59 +03:00
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// already return a clone of the current state
|
|
|
|
|
get state() {
|
|
|
|
|
return this._state = this._clone(this._state);
|
|
|
|
|
}
|
2016-09-19 16:51:05 +03:00
|
|
|
|
2016-08-26 17:37:59 +03:00
|
|
|
// never allow mutation
|
|
|
|
|
set state(value) {
|
|
|
|
|
throw new Error('do not mutate the `.state` directly');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
get(prop?: any) {
|
|
|
|
|
// use our state getter for the clone
|
|
|
|
|
const state = this.state;
|
|
|
|
|
return state.hasOwnProperty(prop) ? state[prop] : state;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
set(prop: string, value: any) {
|
|
|
|
|
// internally mutate our state
|
|
|
|
|
return this._state[prop] = value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2016-10-14 20:10:08 +03:00
|
|
|
private _clone(object: InternalStateType) {
|
2016-08-26 17:37:59 +03:00
|
|
|
// simple object clone
|
2016-09-19 16:51:05 +03:00
|
|
|
return JSON.parse(JSON.stringify(object));
|
2016-08-26 17:37:59 +03:00
|
|
|
}
|
|
|
|
|
}
|