Files
freeCodeCamp/client/sagas/code-storage-saga.js

99 lines
2.2 KiB
JavaScript
Raw Normal View History

import { Observable } from 'rx';
2016-05-27 22:07:10 -07:00
import store from 'store';
import { ofType } from '../../common/utils/get-actions-of-type';
import { updateContents } from '../../common/utils/polyvinyl';
import combineSagas from '../../common/utils/combine-sagas';
import { makeToast } from '../../common/app/toasts/redux/actions';
2016-05-27 22:07:10 -07:00
import types from '../../common/app/routes/challenges/redux/types';
import {
savedCodeFound,
updateMain
2016-05-27 22:07:10 -07:00
} from '../../common/app/routes/challenges/redux/actions';
const legacyPrefixes = [
2016-05-27 22:07:10 -07:00
'Bonfire: ',
'Waypoint: ',
'Zipline: ',
'Basejump: ',
'Checkpoint: '
];
const legacyPostfix = 'Val';
2016-05-27 22:07:10 -07:00
function getCode(id) {
2016-05-27 22:07:10 -07:00
if (store.has(id)) {
return store.get(id);
}
return null;
}
function getLegacyCode(legacy) {
const key = legacy + legacyPostfix;
let code = null;
if (store.has(key)) {
code = '' + store.get(key);
store.remove(key);
2016-05-27 22:07:10 -07:00
return code;
}
return legacyPrefixes.reduce((code, prefix) => {
2016-05-27 22:07:10 -07:00
if (code) {
return code;
}
return store.get(prefix + key);
2016-05-27 22:07:10 -07:00
}, null);
}
function legacyToFile(code, files, key) {
return { [key]: updateContents(code, files[key]) };
}
export function saveCodeSaga(actions, getState) {
return actions
::ofType(types.saveCode)
.map(() => {
const { challengesApp: { id = '', files = {} } } = getState();
store.set(id, files);
return null;
});
}
export function loadCodeSaga(actions$, getState) {
2016-05-27 22:07:10 -07:00
return actions$
::ofType(types.loadCode)
.flatMap(() => {
let finalFiles;
const {
challengesApp: {
id = '',
files = {},
legacyKey = '',
key
}
} = getState();
const codeFound = getCode(id);
2016-05-27 22:07:10 -07:00
if (codeFound) {
finalFiles = codeFound;
} else {
const legacyCode = getLegacyCode(legacyKey);
if (legacyCode) {
finalFiles = legacyToFile(legacyCode, files, key);
}
2016-05-27 22:07:10 -07:00
}
if (finalFiles) {
return Observable.of(
makeToast({
message: 'I found some saved work. Loading now'
}),
savedCodeFound(finalFiles),
updateMain()
);
}
return Observable.empty();
2016-05-27 22:07:10 -07:00
});
}
export default combineSagas(saveCodeSaga, loadCodeSaga);