PLT-6173: Offline redux store (#471)

* PLT-6173: Offline redux store

* Review feedback
This commit is contained in:
Chris Duarte 2017-04-09 17:51:47 -07:00 committed by enahum
parent 22519607d9
commit d206ea68de
29 changed files with 407 additions and 229 deletions

View file

@ -899,3 +899,106 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
## redux-action-buffer
A middleware for redux that buffers all actions into a queue until a breaker condition is met, at which point the queue is released (i.e. actions are triggered).
* HOMEPAGE
* https://github.com/rt2zz/redux-action-buffer
* LICENSE
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
## redux-persist
Persist and rehydrate a redux store.
* HOMEPAGE
* https://github.com/rt2zz/redux-persis
* LICENSE
The MIT License (MIT)
Copyright (c) 2015-present Zack Story
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
## redux-persist-transform-filter
Filter transformator for redux-persist
* HOMEPAGE
* https://github.com/edy/redux-persist-transform-filter
* LICENSE
MIT License
Copyright (c) 2016 Eduard Baun
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Contact GitHub API Training Shop Blog About
---
## jsdom-global
jsdom-global will inject document, window and other DOM API into your Node.js environment. Useful for running, in Node.js, tests that are made for browsers.
* HOMEPAGE
* https://github.com/rstacruz/jsdom-global
* LICENSE
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -15,7 +15,7 @@
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.c2dm.permission.SEND" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="22" />

View file

@ -1,150 +0,0 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import {AsyncStorage} from 'react-native';
import {batchActions} from 'redux-batched-actions';
import {ViewTypes} from 'app/constants';
import {logError, getLogErrorAction} from 'mattermost-redux/actions/errors';
import {ChannelTypes, GeneralTypes, TeamsTypes, UsersTypes} from 'mattermost-redux/constants';
export function loadStorage() {
return async (dispatch, getState) => {
try {
const data = JSON.parse(await AsyncStorage.getItem('storage'));
if (data) {
const {token, url, serverVersion, currentTeamId, ...otherStorage} = data;
const credentials = {token, url};
const currentChannelId = otherStorage[currentTeamId] ? otherStorage[currentTeamId].currentChannelId : '';
const actions = [];
if (credentials) {
actions.push({type: GeneralTypes.RECEIVED_APP_CREDENTIALS, data: credentials});
}
if (serverVersion) {
actions.push({type: GeneralTypes.RECEIVED_SERVER_VERSION, data: serverVersion});
}
if (currentTeamId) {
actions.push({type: TeamsTypes.SELECT_TEAM, data: currentTeamId});
}
if (currentChannelId) {
actions.push({type: ChannelTypes.SELECT_CHANNEL, data: currentChannelId});
}
// Load post drafts if there are any
if (otherStorage.postDrafts) {
Object.keys(otherStorage.postDrafts).forEach((d) => {
actions.push({
type: ViewTypes.SET_POST_DRAFT,
channelId: d,
postDraft: otherStorage.postDrafts[d].draft,
files: otherStorage.postDrafts[d].files
});
});
}
// Load thread drafts if there are any
if (otherStorage.threadDrafts) {
Object.keys(otherStorage.threadDrafts).forEach((d) => {
actions.push({
type: ViewTypes.SET_COMMENT_DRAFT,
rootId: d,
draft: otherStorage.threadDrafts[d].draft,
files: otherStorage.threadDrafts[d].files
});
});
}
if (actions.length) {
dispatch(batchActions(actions), getState);
}
}
} catch (error) {
// Error loading data
dispatch(batchActions([
{
type: ChannelTypes.REMOVED_APP_CREDENTIALS,
error
},
getLogErrorAction(error)
]), getState);
}
};
}
export function flushToStorage() {
return async (dispatch, getState) => {
const state = getState();
// Can add other important items here.
const postDrafts = state.views.channel.drafts;
const threadDrafts = state.views.thread.drafts;
await updateStorage(null, {postDrafts, threadDrafts});
};
}
// Passing in a blank key of null or '' merges the data into the current storage.
// Could maybe use some rework
export async function updateStorage(key, data) {
try {
const currentStorage = JSON.parse(await AsyncStorage.getItem('storage'));
let mergedData;
if (key !== null && key.length > 0) {
const keyData = currentStorage[key];
if (typeof data === 'string') {
mergedData = Object.assign({}, {[key]: data});
} else if (typeof data === 'object') {
mergedData = Object.assign({}, {[key]: {...keyData, ...data}});
}
} else {
mergedData = data;
}
const mergedStorageData = Object.assign({}, currentStorage, mergedData);
await saveStorage(mergedStorageData);
return mergedStorageData;
} catch (error) {
logError(error);
return null;
}
}
async function saveStorage(data) {
try {
await AsyncStorage.setItem('storage', JSON.stringify(data));
} catch (error) {
throw error;
}
}
export function removeStorage() {
return async (dispatch, getState) => {
try {
// Keep the server Url if we have it
const {url} = JSON.parse(await AsyncStorage.getItem('storage'));
if (url) {
await saveStorage({url});
} else {
await AsyncStorage.removeItem('storage');
}
} catch (error) {
logError(error);
}
dispatch({type: UsersTypes.RESET_LOGOUT_STATE}, getState);
};
}
export default {
loadStorage,
removeStorage,
updateStorage
};

View file

@ -4,7 +4,6 @@
import {batchActions} from 'redux-batched-actions';
import {ViewTypes} from 'app/constants';
import {updateStorage} from 'app/actions/storage';
import {
fetchMyChannelsAndMembers,
@ -219,7 +218,11 @@ export function handleSelectChannel(channelId) {
return async (dispatch, getState) => {
const {currentTeamId} = getState().entities.teams;
updateStorage(currentTeamId, {currentChannelId: channelId});
dispatch({
type: ViewTypes.SET_LAST_CHANNEL_FOR_TEAM,
teamId: currentTeamId,
channelId
});
getChannelStats(currentTeamId, channelId)(dispatch, getState);
selectChannel(channelId)(dispatch, getState);
};

View file

@ -1,8 +1,8 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import {GeneralTypes} from 'mattermost-redux/constants';
import {ViewTypes} from 'app/constants';
import {updateStorage} from 'app/actions/storage';
import Client from 'mattermost-redux/client';
export function handleLoginIdChanged(loginId) {
@ -24,10 +24,13 @@ export function handlePasswordChanged(password) {
}
export function handleSuccessfulLogin() {
return async () => {
await updateStorage(null, {
url: Client.getUrl(),
token: Client.getToken()
return async (dispatch) => {
dispatch({
type: GeneralTypes.RECEIVED_APP_CREDENTIALS,
data: {
url: Client.getUrl(),
token: Client.getToken()
}
});
};
}

View file

@ -10,7 +10,6 @@ import {
} from 'app/actions/views/channel';
import {goToChannelView} from 'app/actions/views/load_team';
import {handleTeamChange, selectFirstAvailableTeam} from 'app/actions/views/select_team';
import {updateStorage} from 'app/actions/storage';
import {getClientConfig, getLicenseConfig, setServerVersion} from 'mattermost-redux/actions/general';
import {markChannelAsRead, viewChannel} from 'mattermost-redux/actions/channels';
@ -29,7 +28,6 @@ export function loadConfigAndLicense(serverVersion) {
getClientConfig()(dispatch, getState);
getLicenseConfig()(dispatch, getState);
setServerVersion(serverVersion)(dispatch, getState);
await updateStorage(null, {serverVersion});
};
}

View file

@ -4,7 +4,6 @@
import {batchActions} from 'redux-batched-actions';
import {ChannelTypes, TeamsTypes} from 'mattermost-redux/constants';
import {updateStorage} from 'app/actions/storage';
export function handleTeamChange(team) {
return async (dispatch, getState) => {
@ -13,12 +12,12 @@ export function handleTeamChange(team) {
return;
}
const storage = await updateStorage('currentTeamId', team.id);
const lastChannelForTeam = storage[team.id] ? storage[team.id].currentChannelId : '';
const state = getState();
const lastChannelId = state.views.team.lastChannelForTeam[team.id] || '';
dispatch(batchActions([
{type: TeamsTypes.SELECT_TEAM, data: team.id},
{type: ChannelTypes.SELECT_CHANNEL, data: lastChannelForTeam}
{type: ChannelTypes.SELECT_CHANNEL, data: lastChannelId}
]), getState);
};
}

View file

@ -39,7 +39,6 @@ export default class Root extends Component {
loadConfigAndLicense: PropTypes.func.isRequired,
logout: PropTypes.func.isRequired,
setAppState: PropTypes.func.isRequired,
flushToStorage: PropTypes.func.isRequired,
unrenderDrawer: PropTypes.func.isRequired
}).isRequired
};
@ -48,11 +47,10 @@ export default class Root extends Component {
super(props);
this.handleAppStateChange = this.handleAppStateChange.bind(this);
this.props.actions.setAppState(AppState.currentState === 'active');
}
componentDidMount() {
this.props.actions.setAppState(AppState.currentState === 'active');
AppState.addEventListener('change', this.handleAppStateChange);
EventEmitter.on(Constants.CONFIG_CHANGED, this.handleConfigChanged);
Client.setUserAgent(DeviceInfo.getUserAgent());
@ -75,7 +73,7 @@ export default class Root extends Component {
this.props.actions.setAppState(appState === 'active');
if (appState === 'inactive') {
this.props.actions.flushToStorage();
// TODO: See if we still need this
}
}

View file

@ -7,7 +7,6 @@ import {connect} from 'react-redux';
import Config from 'assets/config.json';
import {closeDrawers, closeModal, goBack, unrenderDrawer} from 'app/actions/navigation';
import {flushToStorage} from 'app/actions/storage';
import {goToNotification, loadConfigAndLicense, queueNotification} from 'app/actions/views/root';
import {setAppState, setDeviceToken} from 'mattermost-redux/actions/general';
import {logout} from 'mattermost-redux/actions/users';
@ -46,7 +45,6 @@ function mapDispatchToProps(dispatch) {
queueNotification,
setAppState,
setDeviceToken,
flushToStorage,
unrenderDrawer
}, dispatch)
};

View file

@ -30,7 +30,9 @@ const ViewTypes = keyMirror({
ADD_FILE_TO_FETCH_CACHE: null,
SET_CHANNEL_LOADER: null
SET_CHANNEL_LOADER: null,
SET_LAST_CHANNEL_FOR_TEAM: null
});
export default ViewTypes;

View file

@ -293,9 +293,13 @@ const state = {
options: [],
visible: false
},
root: {
hydrationComplete: false
},
selectServer: {
serverUrl: Config.DefaultServerUrl
},
team: {},
thread: {
drafts: {}
}

View file

@ -6,14 +6,38 @@ import React from 'react';
import {Provider} from 'react-redux';
import Root from 'app/components/root';
import initialState from 'app/initial_state';
import Router from 'app/navigation/router';
import configureStore from 'app/store';
import initialState from './initial_state';
const store = configureStore(initialState);
export default class Mattermost extends React.Component {
state = {
hydrated: false
}
componentWillMount() {
this.unsubscribeFromStore = store.subscribe(this.listenForHydration);
}
// We need to wait for hydration to occur before load the router.
listenForHydration = () => {
const state = store.getState();
if (state.views.root.hydrationComplete) {
this.unsubscribeFromStore();
this.setState({
hydrated: true
});
}
}
render() {
if (!this.state.hydrated) {
return null;
}
return (
<Provider store={store}>
<Root>

View file

@ -36,8 +36,9 @@ export default class NavigationModal extends PureComponent {
constructor(props) {
super(props);
const top = props.show ? 0 : props.deviceHeight;
this.state = {
top: new Animated.Value(props.deviceHeight),
top: new Animated.Value(top),
opacity: new Animated.Value(100)
};
}

View file

@ -255,7 +255,6 @@ class Router extends Component {
leftDrawerOpen,
leftDrawerRoute,
modal,
rightDrawerRoute,
shouldRenderDrawer,
routes
} = this.props.navigation;
@ -268,11 +267,6 @@ class Router extends Component {
leftDrawerContent = this.renderRoute(leftDrawerRoute);
}
let rightDrawerContent;
if (rightDrawerRoute) {
rightDrawerContent = this.renderRoute(rightDrawerRoute);
}
return (
<View
style={{flex: 1}}
@ -307,7 +301,7 @@ class Router extends Component {
type='displace'
side='right'
disabled={true}
content={rightDrawerContent}
content={null}
tapToClose={true}
openDrawerOffset={50}
onRequestClose={this.props.actions.closeDrawers}

View file

@ -25,7 +25,7 @@ function drafts(state = {}, action) {
}
case ChannelTypes.SELECT_CHANNEL: {
let data = {...state};
if (!data[action.data]) {
if (action.data && !data[action.data]) {
data = {
...state,
[action.data]: {

View file

@ -9,7 +9,9 @@ import i18n from './i18n';
import login from './login';
import notification from './notification';
import optionsModal from './options_modal';
import root from './root';
import selectServer from './select_server';
import team from './team';
import thread from './thread';
export default combineReducers({
@ -19,6 +21,8 @@ export default combineReducers({
login,
notification,
optionsModal,
root,
selectServer,
team,
thread
});

View file

@ -0,0 +1,18 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import {combineReducers} from 'redux';
import {Constants} from 'mattermost-redux/constants';
function hydrationComplete(state = false, action) {
switch (action.type) {
case Constants.STORE_REHYDRATION_COMPLETE:
return true;
default:
return state;
}
}
export default combineReducers({
hydrationComplete
});

View file

@ -0,0 +1,33 @@
// Copyright (c) 2017 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import {combineReducers} from 'redux';
import {TeamsTypes} from 'mattermost-redux/constants';
import {ViewTypes} from 'app/constants';
function lastTeamId(state = '', action) {
switch (action.type) {
case TeamsTypes.SELECT_TEAM:
return action.data;
default:
return state;
}
}
function lastChannelForTeam(state = {}, action) {
switch (action.type) {
case ViewTypes.SET_LAST_CHANNEL_FOR_TEAM:
return {
...state,
[action.teamId]: action.channelId
};
default:
return state;
}
}
export default combineReducers({
lastTeamId,
lastChannelForTeam
});

View file

@ -2,7 +2,6 @@
// See License.txt for license information.
import React, {PropTypes, PureComponent} from 'react';
import {AsyncStorage} from 'react-native';
import Orientation from 'react-native-orientation';
import Loading from 'app/components/loading';
@ -18,10 +17,9 @@ export default class Root extends PureComponent {
goToLoadTeam: PropTypes.func,
goToSelectServer: PropTypes.func,
handleServerUrlChanged: PropTypes.func.isRequired,
loadStorage: PropTypes.func,
removeStorage: PropTypes.func,
setStoreFromLocalData: PropTypes.func
}).isRequired
}).isRequired,
hydrationComplete: PropTypes.bool.isRequired
};
static navigationProps = {
@ -31,20 +29,16 @@ export default class Root extends PureComponent {
componentDidMount() {
Orientation.lockToPortrait();
// Any initialization logic for navigation, setting up the client, etc should go here
this.init();
this.loadStoreAndScene(this.props.credentials);
setTimeout(() => {
this.handleCloseSplashScreen();
}, 1000);
}
componentWillReceiveProps(nextProps) {
if (this.props.logoutRequest.status === RequestStatus.STARTED &&
nextProps.logoutRequest.status === RequestStatus.SUCCESS) {
this.props.actions.removeStorage();
} else if (this.props.logoutRequest.status === RequestStatus.SUCCESS &&
if (this.props.logoutRequest.status === RequestStatus.SUCCESS &&
nextProps.logoutRequest.status === RequestStatus.NOT_STARTED) {
this.init();
this.loadStoreAndScene(nextProps.credentials);
}
}
@ -58,40 +52,18 @@ export default class Root extends PureComponent {
SplashScreen.close(Object.assign({}, opts, options));
};
init = () => {
if (this.props.logoutRequest.status === RequestStatus.SUCCESS) {
this.props.actions.removeStorage().then(() => {
setTimeout(this.loadStoreAndScene, 1000);
});
loadStoreAndScene = (credentials = {}) => {
if (credentials.token && credentials.url) {
// Will probably need to make this optimistic since we
// assume that the stored token is good.
this.props.actions.setStoreFromLocalData(credentials);
this.props.actions.goToLoadTeam();
} else {
this.loadStoreAndScene();
this.selectServer();
}
};
loadStoreAndScene = () => {
this.props.actions.loadStorage().then(() => {
if (this.props.credentials.token && this.props.credentials.url) {
this.props.actions.setStoreFromLocalData(this.props.credentials).then(() => {
if (this.props.loginRequest.status === RequestStatus.SUCCESS) {
this.props.actions.goToLoadTeam();
} else {
this.selectServer();
}
});
} else {
this.selectServer();
}
});
};
selectServer = async () => {
const storage = await AsyncStorage.getItem('storage');
if (storage) {
const {url} = JSON.parse(await AsyncStorage.getItem('storage'));
if (url) {
await this.props.actions.handleServerUrlChanged(url);
}
}
this.props.actions.goToSelectServer();
};

View file

@ -5,7 +5,6 @@ import {bindActionCreators} from 'redux';
import navigationSceneConnect from '../navigationSceneConnect';
import {loadStorage, removeStorage} from 'app/actions/storage';
import {goToSelectServer} from 'app/actions/views/root';
import {handleServerUrlChanged} from 'app/actions/views/select_server';
import {goToLoadTeam} from 'app/actions/navigation';
@ -18,6 +17,7 @@ function mapStateToProps(state, ownProps) {
return {
...ownProps,
credentials: state.entities.general.credentials,
hydrationComplete: state.views.root.hydrationComplete,
logoutRequest: state.requests.users.logout,
loginRequest: state.requests.users.login
};
@ -29,8 +29,6 @@ function mapDispatchToProps(dispatch) {
goToLoadTeam,
goToSelectServer,
handleServerUrlChanged,
loadStorage,
removeStorage,
setStoreFromLocalData
}, dispatch)
};

View file

@ -1,13 +1,124 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import {batchActions} from 'redux-batched-actions';
import {AsyncStorage} from 'react-native';
import {configureOfflineServiceStore} from 'mattermost-redux/store';
import {Constants, RequestStatus} from 'mattermost-redux/constants';
import {createBlacklistFilter} from 'redux-persist-transform-filter';
import {createTransform, persistStore} from 'redux-persist';
import {ViewTypes} from 'app/constants';
import appReducer from 'app/reducers';
import configureServiceStore from 'mattermost-redux/store';
import {transformSet} from './utils';
function getAppReducer() {
return require('../../app/reducers'); // eslint-disable-line global-require
}
export default function configureStore(preloadedState) {
return configureServiceStore(preloadedState, appReducer, getAppReducer);
const usersSetTransform = [
'profilesInChannel',
'profilesNotInChannel',
'profilesInTeam'
];
const teamSetTransform = [
'membersInTeam'
];
const setTransforms = [
...usersSetTransform,
...teamSetTransform
];
export default function configureStore(initialState) {
const viewsBlackListFilter = createBlacklistFilter(
'views',
['login']
);
const setTransformer = createTransform(
(inboundState, key) => {
if (key === 'entities') {
const state = {...inboundState};
for (const prop in state) {
if (state.hasOwnProperty(prop)) {
state[prop] = transformSet(state[prop], setTransforms);
}
}
return state;
}
return inboundState;
},
(outboundState, key) => {
if (key === 'entities') {
const state = {...outboundState};
for (const prop in state) {
if (state.hasOwnProperty(prop)) {
state[prop] = transformSet(state[prop], setTransforms, false);
}
}
return state;
}
return outboundState;
}
);
const offlineOptions = {
persist: (store, options) => {
const persistor = persistStore(store, {storage: AsyncStorage, ...options}, () => {
store.dispatch({
type: Constants.STORE_REHYDRATION_COMPLETE,
complete: true
});
});
let purging = false;
// check to see if the logout request was successful
store.subscribe(() => {
const state = store.getState();
if (state.requests.users.logout.status === RequestStatus.SUCCESS && !purging) {
purging = true;
persistor.purge();
store.dispatch(batchActions([
{
type: Constants.OFFLINE_STORE_RESET,
data: initialState
},
{
type: ViewTypes.SERVER_URL_CHANGED,
serverUrl: state.views.selectServer.serverUrl
}
]));
setTimeout(() => {
purging = false;
}, 500);
}
});
return persistor;
},
persistOptions: {
autoRehydrate: {
log: false
},
blacklist: ['errors', 'navigation', 'offline', 'requests'],
debounce: 500,
transforms: [
setTransformer,
viewsBlackListFilter
]
}
};
return configureOfflineServiceStore(appReducer, offlineOptions, getAppReducer);
}

42
app/store/utils.js Normal file
View file

@ -0,0 +1,42 @@
// Copyright (c) 2017 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
function transformFromSet(incoming) {
const state = {...incoming};
for (const key in state) {
if (state.hasOwnProperty(key)) {
if (state[key] instanceof Set) {
state[key] = Array.from([...state[key]]);
}
}
}
return state;
}
function transformToSet(incoming) {
const state = {...incoming};
for (const key in state) {
if (state.hasOwnProperty(key)) {
state[key] = new Set(state[key]);
}
}
return state;
}
export function transformSet(incoming, setTransforms, toStorage = true) {
const state = {...incoming};
const transformer = toStorage ? transformFromSet : transformToSet;
for (const key in state) {
if (state.hasOwnProperty(key) && setTransforms.includes(key)) {
state[key] = transformer(state[key]);
}
}
return state;
}

View file

@ -31,6 +31,8 @@
"react-redux": "5.0.3",
"redux": "3.6.0",
"redux-batched-actions": "0.1.5",
"redux-persist": "4.6.0",
"redux-persist-transform-filter": "0.0.9",
"redux-thunk": "2.2.0",
"reselect": "3.0.0",
"semver": "5.3.0"
@ -51,6 +53,8 @@
"eslint-plugin-react": "6.10.3",
"fetch-mock": "5.9.4",
"form-data": "2.1.2",
"jsdom": "9.12.0",
"jsdom-global": "2.1.1",
"mocha": "3.2.0",
"mocha-react-native": "0.5.0",
"react-addons-test-utils": "15.4.2",

View file

@ -6,10 +6,13 @@ import assert from 'assert';
import * as Actions from 'app/actions/views/login';
import configureStore from 'app/store';
import TestHelper from 'test/test_helper';
describe('Actions.Views.Login', () => {
let store;
beforeEach(() => {
beforeEach(async () => {
store = configureStore();
await TestHelper.wait();
});
it('handleLoginIdChanged', async () => {

View file

@ -6,10 +6,13 @@ import assert from 'assert';
import * as Actions from 'app/actions/views/options_modal';
import configureStore from 'app/store';
import TestHelper from 'test/test_helper';
describe('Actions.Views.OptionsModal', () => {
let store;
beforeEach(() => {
beforeEach(async () => {
store = configureStore();
await TestHelper.wait();
});
it('openModal', async () => {

View file

@ -6,9 +6,12 @@ import assert from 'assert';
import * as Actions from 'app/actions/views/select_server';
import configureStore from 'app/store';
import TestHelper from 'test/test_helper';
describe('Actions.Views.SelectServer', () => {
it('handleServerUrlChanged', async () => {
const store = configureStore();
await TestHelper.wait();
await Actions.handleServerUrlChanged('https://mattermost.example.com')(store.dispatch, store.getState);
const serverUrl = store.getState().views.selectServer.serverUrl;

View file

@ -6,9 +6,12 @@ import assert from 'assert';
import * as ThreadActions from 'app/actions/views/thread';
import configureStore from 'app/store';
import TestHelper from 'test/test_helper';
describe('Actions.Views.Thread', () => {
it('handleCommentDraftChanged', async () => {
const store = configureStore();
await TestHelper.wait();
await ThreadActions.handleCommentDraftChanged('1234', 'draft1')(store.dispatch, store.getState);

View file

@ -5,4 +5,5 @@
--require react-native-mock/mock.js
--require react-native-svg-mock/mock
--require babel-polyfill
--require jsdom-global/register
--recursive

View file

@ -129,6 +129,12 @@ class TestHelper {
post: this.basicPost
};
};
wait = () => {
return new Promise((resolve) => {
setTimeout(() => resolve(), 1000);
});
}
}
export default new TestHelper();