Files
freeCodeCamp/client/src/redux/settings/update-legacy-certificate-saga.js

89 lines
2.5 KiB
JavaScript
Raw Normal View History

2019-03-26 07:12:20 +03:00
import { takeEvery, select, call, put } from 'redux-saga/effects';
import { putUpdateLegacyCertificate } from '../../utils/ajax';
2019-03-26 07:12:20 +03:00
import { completedChallengesSelector } from '../';
import { legacyProjectMap } from '../../resources/certProjectMap';
import { createFlashMessage } from '../../components/Flash/redux';
import {
updateLegacyCertificateComplete,
updateLegacyCertificateError
} from './';
2019-03-26 07:12:20 +03:00
const completedChallenges = state => completedChallengesSelector(state);
2019-03-26 07:12:20 +03:00
function* updateLegacyCertificateSaga({ payload }) {
// find which certificate the challenges belong to
let legacyCert;
let certs = Object.keys(legacyProjectMap);
let loopBreak = false;
for (let i of certs) {
for (let j of legacyProjectMap[i]) {
if (j.title === Object.keys(payload)[0]) {
console.log(j.title);
loopBreak = true;
legacyCert = i;
break;
}
}
if (loopBreak) {
break;
}
}
// make an object with keys as challenge ids and values as solutions
let idsToSolutions = {};
for (let i of Object.keys(payload)) {
for (let j of legacyProjectMap[legacyCert]) {
if (i === j.title) {
console.log(payload[i]);
idsToSolutions[j.id] = payload[i];
break;
}
}
}
// find how many challnegs have been updated and how many are new
let completed = yield select(completedChallenges);
let newSubmissions = 0;
let challengesToUpdate = {};
let newChalleneFound = true;
for (let j of Object.keys(idsToSolutions)) {
for (let i of completed) {
if (i.id === j) {
if (idsToSolutions[j] !== i.solution) {
challengesToUpdate[j] = idsToSolutions[j];
}
newChalleneFound = false;
break;
}
}
if (newChalleneFound && idsToSolutions[j] !== '') {
challengesToUpdate[j] = idsToSolutions[j];
newSubmissions++;
}
newChalleneFound = true;
}
console.log(newSubmissions);
2019-03-26 07:12:20 +03:00
// shape the body of the http calls so it is consumable by api
const body = {
projects: {
2019-03-26 07:12:20 +03:00
[legacyCert]: challengesToUpdate
}
};
try {
2019-03-26 07:12:20 +03:00
const response = yield call(putUpdateLegacyCertificate, body);
yield put(
2019-03-26 07:12:20 +03:00
updateLegacyCertificateComplete({ updatedChallenges: challengesToUpdate })
);
yield put(createFlashMessage(response));
} catch (e) {
2019-03-26 07:12:20 +03:00
yield put(updateLegacyCertificateError(e));
}
}
export function createUpdateLegacyCertificateSaga(types) {
return [
takeEvery(types.updateLegacyCertificate, updateLegacyCertificateSaga)
];
}