Skip to content

Instantly share code, notes, and snippets.

@maolion
Last active July 7, 2016 22:12
Show Gist options
  • Select an option

  • Save maolion/00cca94091d532d3772004dbcabd3596 to your computer and use it in GitHub Desktop.

Select an option

Save maolion/00cca94091d532d3772004dbcabd3596 to your computer and use it in GitHub Desktop.
/**
* 框架数据存储层
* @author lion
* @email maolion.j@gmail.com
*/
import * as Redux from 'redux';
import reduxThunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { routerReducer } from 'react-native-router';
import * as Helpers from '../../utils/helpers';
export default class Store {
public static OVERWRITE = "STORE_OVERWRITE_APP_TARGET_DATA";
public static UPDATE = "STORE_UPDATE_APP_TARGET_DATA";
public static DELETE = "STORE_DELETE_APP_TARGET_DATA";
private _store: Redux.Store<any>;
constructor() {
this._store = this._createStore();
}
public get<T>(ns: string): T {
let nsChain = ns.split('.').reverse();
let data = this._store.getState().appReducer;
while (nsChain.length) {
data = data[nsChain.pop()];
if (!data) {
break;
}
}
return data;
}
public dispatch(action: StoreAction) {
this._store.dispatch(action);
}
private _createStore() {
const storeEnhacers:any[] = [];
const combinedCreateStore =
Redux.compose.apply(Redux, storeEnhacers)(Redux.createStore);
const middlewares: Redux.Middleware[] = [
reduxThunk
];
if ((global as any).__DEV__) {
middlewares.push(createLogger());
}
const createStoreWithMiddleware =
Redux.applyMiddleware(...middlewares)(combinedCreateStore);
return createStoreWithMiddleware(this._getRootReducer());
}
private _getRootReducer() {
return Redux.combineReducers({
routerReducer,
appReducer
});
}
}
function getLeafObject(obj: any, ns: string, param: any) {
let nsChain = Helpers.foramt(ns, param).split(".");
let leafKey = nsChain.pop();
nsChain.reverse();
while (nsChain.length) {
let key = nsChain.pop();
obj = obj[key];
if (!obj || typeof obj != 'object') {
obj = obj[key] = {};
}
}
return {
key: leafKey,
value: obj[leafKey],
parent: obj
};
}
function appReducer(state: any, action: StoreAction) {
switch (action.type) {
case Store.OVERWRITE: {
const target = getLeafObject(
state,
action.meta.storeKey,
action.meta.param
);
target.parent[target.key] = action.payload;
break;
}
case Store.UPDATE: {
const target = getLeafObject(
state,
action.meta.storekey,
action.meta.param
);
target.parent[target.key] = Object.assign(
target.value || {},
action.payload
);
break;
}
case Store.DELETE:
const target = getLeafObject(
state,
action.meta.storeKey,
action.meta.param
);
delete target.parent[target.key];
break;
}
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment