diff --git a/lib/routing.js b/lib/routing.js index d04390e..3f539a1 100644 --- a/lib/routing.js +++ b/lib/routing.js @@ -46,20 +46,43 @@ const reverseMappings = mappings.map(mapping => }) ) +const serializeState = state => { + const stateString = encodeURIComponent(JSON.stringify(state)) + + return typeof window !== 'undefined' + ? btoa(stateString) + : Buffer.from(stateString).toString('base64') +} + +const deserializeState = serializedState => { + let stateString + if (typeof window !== 'undefined') { + stateString = atob(serializedState) + } else { + stateString = Buffer.from(serializedState, 'base64').toString() + } + + return JSON.parse(decodeURIComponent(stateString)) +} + const keysToQuery = keys => `?${Object.keys(keys) .map(key => `${key}=${keys[key]}`) .join('&')}` export const getQueryStringState = query => { - const state = mapper.map(mappings, query) - deserializeCode(state) + if (query.state) { + return deserializeState(query.state) + } else { + const state = mapper.map(mappings, query) + deserializeCode(state) - Object.keys(state).forEach(key => { - if (state[key] === '') state[key] = undefined - }) + Object.keys(state).forEach(key => { + if (state[key] === '') state[key] = undefined + }) - return state + return state + } } export const updateQueryString = state => {