feat: let users save cert project code to db (#44700)
* feat: let users save cert project code to db fix: move getChallenges call out of request function so it only runs once fix: use FlashMessages enum fix: transform challengeFiles earlier test: make tribute page use multifile editor stuff I was playing with - revert this to get it to a working state refactor: allow undefined editableRegionBoundaries fix: save history history is not necessarily ["name.ext"] and using the incorrect history could cause weird bugs fix: replace files -> challengeFiles on the client refactor: DRY out ajax fix: use file -> challengefile map refactor: rename ajax types fix: alphatize flash-messages.ts revert: tribute page project fix: remove logs fix: prettier fix: cypress fix: prettier fix: remove submitComplete action fix: block UI for new projects fix: handle code size * fix: catch undefined files * fix: don't default to undefined when it's already the default * fix: only update savedChallenges if applicable * fix: dehumidify backend + fine tune nearby stuff * fix: prop-types * fix: dehumidify sagas * fix: variable name * fix: types * Apply suggestions from code review Co-authored-by: Shaun Hamilton <shauhami020@gmail.com> * fix: typo * fix: prettier * fix: props types * fix: flash messages * Update client/src/utils/challenge-request-helpers.ts Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * chore: rename function uniformize -> standardize * fix: flash message * fix: add link to forum on flash messages Co-authored-by: Shaun Hamilton <shauhami020@gmail.com> Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
This commit is contained in:
@@ -58,6 +58,7 @@
|
||||
"resubscribe": "You can click here to resubscribe",
|
||||
"click-here": "Click here to sign in",
|
||||
"save": "Save",
|
||||
"save-code": "Save your Code",
|
||||
"no-thanks": "No thanks",
|
||||
"yes-please": "Yes please",
|
||||
"update-email": "Update my Email",
|
||||
@@ -529,7 +530,11 @@
|
||||
"start-project-err": "Something went wrong trying to start the project. Please try again.",
|
||||
"complete-project-first": "You must complete the project first.",
|
||||
"local-code-save-error": "Oops, your code did not save, your browser's local storage may be full.",
|
||||
"local-code-saved": "Saved! Your code was saved to your browser's local storage."
|
||||
"local-code-saved": "Saved! Your code was saved to your browser's local storage.",
|
||||
"code-saved": "Your code was saved to the database. It will be here when you return.",
|
||||
"code-save-error": "An error occurred trying to save your code.",
|
||||
"challenge-save-too-big": "Sorry, you cannot save your code. Your code is {{user-size}} bytes. We allow a maximum of {{max-size}} bytes. Please make your code smaller and try again or request assistance on https://forum.freecodecamp.org",
|
||||
"challenge-submit-too-big": "Sorry, you cannot submit your code. Your code is {{user-size}} bytes. We allow a maximum of {{max-size}} bytes. Please make your code smaller and try again or request assistance on https://forum.freecodecamp.org"
|
||||
},
|
||||
"validation": {
|
||||
"max-characters": "There is a maximum limit of 288 characters, you have {{charsLeft}} left",
|
||||
|
@@ -5,6 +5,10 @@ export enum FlashMessages {
|
||||
CertClaimSuccess = 'flash.cert-claim-success',
|
||||
CertificateMissing = 'flash.certificate-missing',
|
||||
CertsPrivate = 'flash.certs-private',
|
||||
ChallengeSaveTooBig = 'flash.challenge-save-too-big',
|
||||
ChallengeSubmitTooBig = 'flash.challenge-submit-too-big',
|
||||
CodeSaved = 'flash.code-saved',
|
||||
CodeSaveError = 'flash.code-save-error',
|
||||
CompleteProjectFirst = 'flash.complete-project-first',
|
||||
DeleteTokenErr = 'flash.delete-token-err',
|
||||
EmailValid = 'flash.email-valid',
|
||||
|
@@ -209,7 +209,7 @@ class DefaultLayout extends Component<DefaultLayoutProps> {
|
||||
removeFlashMessage={removeFlashMessage}
|
||||
/>
|
||||
) : null}
|
||||
{children}
|
||||
{fetchState.complete && children}
|
||||
</div>
|
||||
{showFooter && <Footer />}
|
||||
</div>
|
||||
|
@@ -47,6 +47,7 @@ const userProps = {
|
||||
name: 'string',
|
||||
picture: 'string',
|
||||
points: 1,
|
||||
savedChallenges: [],
|
||||
sendQuincyEmail: true,
|
||||
sound: true,
|
||||
theme: Themes.Default,
|
||||
|
@@ -34,7 +34,8 @@ export const actionTypes = createTypes(
|
||||
...createAsyncTypes('showCert'),
|
||||
...createAsyncTypes('reportUser'),
|
||||
...createAsyncTypes('postChargeStripeCard'),
|
||||
...createAsyncTypes('deleteUserToken')
|
||||
...createAsyncTypes('deleteUserToken'),
|
||||
...createAsyncTypes('saveChallenge')
|
||||
],
|
||||
ns
|
||||
);
|
||||
|
@@ -22,6 +22,7 @@ import { createShowCertSaga } from './show-cert-saga';
|
||||
import { createSoundModeSaga } from './sound-mode-saga';
|
||||
import updateCompleteEpic from './update-complete-epic';
|
||||
import { createUserTokenSaga } from './user-token-saga';
|
||||
import { createSaveChallengeSaga } from './save-challenge-saga';
|
||||
|
||||
export const MainApp = 'app';
|
||||
|
||||
@@ -82,7 +83,8 @@ export const sagas = [
|
||||
...createShowCertSaga(actionTypes),
|
||||
...createReportUserSaga(actionTypes),
|
||||
...createSoundModeSaga({ ...actionTypes, ...settingsTypes }),
|
||||
...createUserTokenSaga(actionTypes)
|
||||
...createUserTokenSaga(actionTypes),
|
||||
...createSaveChallengeSaga(actionTypes)
|
||||
];
|
||||
|
||||
export const appMount = createAction(actionTypes.appMount);
|
||||
@@ -121,6 +123,11 @@ export const submitComplete = createAction(actionTypes.submitComplete);
|
||||
export const updateComplete = createAction(actionTypes.updateComplete);
|
||||
export const updateFailed = createAction(actionTypes.updateFailed);
|
||||
|
||||
export const saveChallenge = createAction(actionTypes.saveChallenge);
|
||||
export const saveChallengeComplete = createAction(
|
||||
actionTypes.saveChallengeComplete
|
||||
);
|
||||
|
||||
export const acceptTerms = createAction(actionTypes.acceptTerms);
|
||||
export const acceptTermsComplete = createAction(
|
||||
actionTypes.acceptTermsComplete
|
||||
@@ -188,6 +195,8 @@ export const updateCurrentChallengeId = createAction(
|
||||
actionTypes.updateCurrentChallengeId
|
||||
);
|
||||
|
||||
export const savedChallengesSelector = state =>
|
||||
userSelector(state).savedChallenges || [];
|
||||
export const completedChallengesSelector = state =>
|
||||
userSelector(state).completedChallenges || [];
|
||||
export const partiallyCompletedChallengesSelector = state =>
|
||||
@@ -637,9 +646,12 @@ export const reducer = handleActions(
|
||||
}
|
||||
}),
|
||||
[actionTypes.submitComplete]: (state, { payload }) => {
|
||||
let submittedchallenges = [{ ...payload, completedDate: Date.now() }];
|
||||
if (payload.challArray) {
|
||||
submittedchallenges = payload.challArray;
|
||||
const { submittedChallenge, savedChallenges } = payload;
|
||||
let submittedchallenges = [
|
||||
{ ...submittedChallenge, completedDate: Date.now() }
|
||||
];
|
||||
if (submittedChallenge.challArray) {
|
||||
submittedchallenges = submittedChallenge.challArray;
|
||||
}
|
||||
const { appUsername } = state;
|
||||
return {
|
||||
@@ -655,7 +667,9 @@ export const reducer = handleActions(
|
||||
...state.user[appUsername].completedChallenges
|
||||
],
|
||||
'id'
|
||||
)
|
||||
),
|
||||
savedChallenges:
|
||||
savedChallenges ?? savedChallengesSelector(state[MainApp])
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -702,6 +716,19 @@ export const reducer = handleActions(
|
||||
...state,
|
||||
currentChallengeId: payload
|
||||
}),
|
||||
[actionTypes.saveChallengeComplete]: (state, { payload }) => {
|
||||
const { appUsername } = state;
|
||||
return {
|
||||
...state,
|
||||
user: {
|
||||
...state.user,
|
||||
[appUsername]: {
|
||||
...state.user[appUsername],
|
||||
savedChallenges: payload
|
||||
}
|
||||
}
|
||||
};
|
||||
},
|
||||
[settingsTypes.submitNewUsernameComplete]: (state, { payload }) =>
|
||||
payload
|
||||
? {
|
||||
|
@@ -50,6 +50,12 @@ export const UserPropType = PropTypes.shape({
|
||||
description: PropTypes.string
|
||||
})
|
||||
),
|
||||
savedChallenges: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
id: PropTypes.string,
|
||||
challengeFiles: PropTypes.array
|
||||
})
|
||||
),
|
||||
sendQuincyEmail: PropTypes.bool,
|
||||
sound: PropTypes.bool,
|
||||
theme: PropTypes.string,
|
||||
@@ -267,6 +273,7 @@ export type User = {
|
||||
portfolio: Portfolio[];
|
||||
profileUI: ProfileUI;
|
||||
progressTimestamps: Array<unknown>;
|
||||
savedChallenges: SavedChallenges;
|
||||
sendQuincyEmail: boolean;
|
||||
sound: boolean;
|
||||
theme: Themes;
|
||||
@@ -310,6 +317,23 @@ export type ClaimedCertifications = {
|
||||
isMachineLearningPyCertV7: boolean;
|
||||
};
|
||||
|
||||
export type SavedChallenges = SavedChallenge[];
|
||||
|
||||
export type SavedChallenge = {
|
||||
id: string;
|
||||
challengeFiles: SavedChallengeFiles;
|
||||
};
|
||||
|
||||
export type SavedChallengeFile = {
|
||||
fileKey: string;
|
||||
ext: Ext;
|
||||
name: string;
|
||||
history?: string[];
|
||||
contents: string;
|
||||
};
|
||||
|
||||
export type SavedChallengeFiles = SavedChallengeFile[];
|
||||
|
||||
export type CompletedChallenge = {
|
||||
id: string;
|
||||
solution?: string | null;
|
||||
@@ -359,8 +383,8 @@ export type ChallengeFile = {
|
||||
fileKey: string;
|
||||
ext: Ext;
|
||||
name: string;
|
||||
editableRegionBoundaries: number[];
|
||||
usesMultifileEditor: boolean;
|
||||
editableRegionBoundaries?: number[];
|
||||
usesMultifileEditor?: boolean;
|
||||
error: null | string;
|
||||
head: string;
|
||||
tail: string;
|
||||
|
68
client/src/redux/save-challenge-saga.js
Normal file
68
client/src/redux/save-challenge-saga.js
Normal file
@@ -0,0 +1,68 @@
|
||||
import { call, takeEvery, put, select } from 'redux-saga/effects';
|
||||
import { postSaveChallenge, mapFilesToChallengeFiles } from '../utils/ajax';
|
||||
import {
|
||||
challengeDataSelector,
|
||||
challengeMetaSelector
|
||||
} from '../templates/Challenges/redux';
|
||||
import { createFlashMessage } from '../components/Flash/redux';
|
||||
import { challengeTypes } from '../../utils/challenge-types';
|
||||
import { FlashMessages } from '../components/Flash/redux/flash-messages';
|
||||
import {
|
||||
standardizeRequestBody,
|
||||
getStringSizeInBytes,
|
||||
bodySizeFits,
|
||||
MAX_BODY_SIZE
|
||||
} from '../utils/challenge-request-helpers';
|
||||
import { saveChallengeComplete } from './';
|
||||
|
||||
export function* saveChallengeSaga() {
|
||||
const { id, challengeType } = yield select(challengeMetaSelector);
|
||||
const { challengeFiles } = yield select(challengeDataSelector);
|
||||
|
||||
// only allow saving of multiFileCertProject's
|
||||
if (challengeType === challengeTypes.multiFileCertProject) {
|
||||
const body = standardizeRequestBody({ id, challengeFiles, challengeType });
|
||||
const bodySizeInBytes = getStringSizeInBytes(body);
|
||||
|
||||
if (!bodySizeFits(bodySizeInBytes)) {
|
||||
return yield put(
|
||||
createFlashMessage({
|
||||
type: 'danger',
|
||||
message: FlashMessages.ChallengeSaveTooBig,
|
||||
variables: { 'max-size': MAX_BODY_SIZE, 'user-size': bodySizeInBytes }
|
||||
})
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
const response = yield call(postSaveChallenge, body);
|
||||
|
||||
if (response?.message) {
|
||||
yield put(createFlashMessage(response));
|
||||
} else if (response?.savedChallenges) {
|
||||
yield put(
|
||||
saveChallengeComplete(
|
||||
mapFilesToChallengeFiles(response.savedChallenges)
|
||||
)
|
||||
);
|
||||
yield put(
|
||||
createFlashMessage({
|
||||
type: 'success',
|
||||
message: FlashMessages.CodeSaved
|
||||
})
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
yield put(
|
||||
createFlashMessage({
|
||||
type: 'danger',
|
||||
message: FlashMessages.CodeSaveError
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createSaveChallengeSaga(types) {
|
||||
return [takeEvery(types.saveChallenge, saveChallengeSaga)];
|
||||
}
|
@@ -8,6 +8,7 @@ import EditorTabs from './editor-tabs';
|
||||
interface ActionRowProps {
|
||||
block: string;
|
||||
hasNotes: boolean;
|
||||
isMultiFileCertProject: boolean;
|
||||
showConsole: boolean;
|
||||
showNotes: boolean;
|
||||
showPreview: boolean;
|
||||
@@ -22,6 +23,7 @@ const mapDispatchToProps = {
|
||||
|
||||
const ActionRow = ({
|
||||
hasNotes,
|
||||
isMultiFileCertProject,
|
||||
togglePane,
|
||||
showNotes,
|
||||
showPreview,
|
||||
@@ -38,9 +40,11 @@ const ActionRow = ({
|
||||
</div>
|
||||
<div className='tabs-row'>
|
||||
<EditorTabs />
|
||||
<button className='restart-step-tab' onClick={resetChallenge}>
|
||||
{t('learn.editor-tabs.restart-step')}
|
||||
</button>
|
||||
{!isMultiFileCertProject && (
|
||||
<button className='restart-step-tab' onClick={resetChallenge}>
|
||||
{t('learn.editor-tabs.restart-step')}
|
||||
</button>
|
||||
)}
|
||||
<div className='panel-display-tabs'>
|
||||
<button
|
||||
aria-expanded={showConsole ? 'true' : 'false'}
|
||||
|
@@ -110,6 +110,7 @@ const DesktopLayout = (props: DesktopLayoutProps): JSX.Element => {
|
||||
<ActionRow
|
||||
block={block}
|
||||
hasNotes={hasNotes}
|
||||
isMultiFileCertProject={isMultiFileCertProject}
|
||||
showConsole={showConsole}
|
||||
showNotes={showNotes}
|
||||
showPreview={showPreview}
|
||||
|
@@ -82,7 +82,7 @@ interface EditorProps {
|
||||
updateFile: (object: {
|
||||
fileKey: FileKey;
|
||||
editorValue: string;
|
||||
editableRegionBoundaries: number[] | null;
|
||||
editableRegionBoundaries?: number[];
|
||||
}) => void;
|
||||
usesMultifileEditor: boolean;
|
||||
}
|
||||
@@ -632,10 +632,12 @@ const Editor = (props: EditorProps): JSX.Element => {
|
||||
// has changed or if content is dragged between regions)
|
||||
|
||||
const coveringRange = getLinesCoveringEditableRegion();
|
||||
const editableRegionBoundaries = coveringRange && [
|
||||
coveringRange.startLineNumber - 1,
|
||||
coveringRange.endLineNumber + 1
|
||||
];
|
||||
const editableRegionBoundaries =
|
||||
(coveringRange && [
|
||||
coveringRange.startLineNumber - 1,
|
||||
coveringRange.endLineNumber + 1
|
||||
]) ??
|
||||
undefined;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
if (player.current.sampler?.loaded && player.current.shouldPlay) {
|
||||
|
@@ -12,12 +12,12 @@ import { challengeTypes } from '../../../../utils/challenge-types';
|
||||
import LearnLayout from '../../../components/layouts/learn';
|
||||
|
||||
import {
|
||||
ChallengeFile,
|
||||
ChallengeFiles,
|
||||
ChallengeMeta,
|
||||
ChallengeNode,
|
||||
CompletedChallenge,
|
||||
ResizeProps,
|
||||
SavedChallengeFiles,
|
||||
Test
|
||||
} from '../../../redux/prop-types';
|
||||
import { isContained } from '../../../utils/is-contained';
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
openModal,
|
||||
setEditorFocusability
|
||||
} from '../redux';
|
||||
import { savedChallengesSelector } from '../../../redux';
|
||||
import { getGuideUrl } from '../utils';
|
||||
import MultifileEditor from './MultifileEditor';
|
||||
import DesktopLayout from './desktop-layout';
|
||||
@@ -62,7 +63,8 @@ const mapStateToProps = createStructuredSelector({
|
||||
challengeFiles: challengeFilesSelector,
|
||||
tests: challengeTestsSelector,
|
||||
output: consoleOutputSelector,
|
||||
isChallengeCompleted: isChallengeCompletedSelector
|
||||
isChallengeCompleted: isChallengeCompletedSelector,
|
||||
savedChallenges: savedChallengesSelector
|
||||
});
|
||||
|
||||
const mapDispatchToProps = (dispatch: Dispatch) =>
|
||||
@@ -86,7 +88,7 @@ const mapDispatchToProps = (dispatch: Dispatch) =>
|
||||
interface ShowClassicProps {
|
||||
cancelTests: () => void;
|
||||
challengeMounted: (arg0: string) => void;
|
||||
createFiles: (arg0: ChallengeFile[]) => void;
|
||||
createFiles: (arg0: ChallengeFiles | SavedChallengeFiles) => void;
|
||||
data: { challengeNode: ChallengeNode };
|
||||
executeChallenge: (options?: { showCompletionModal: boolean }) => void;
|
||||
challengeFiles: ChallengeFiles;
|
||||
@@ -107,6 +109,7 @@ interface ShowClassicProps {
|
||||
openModal: (modal: string) => void;
|
||||
setEditorFocusability: (canFocus: boolean) => void;
|
||||
previewMounted: () => void;
|
||||
savedChallenges: CompletedChallenge[];
|
||||
}
|
||||
|
||||
interface ShowClassicState {
|
||||
@@ -256,6 +259,7 @@ class ShowClassic extends Component<ShowClassicProps, ShowClassicState> {
|
||||
initTests,
|
||||
updateChallengeMeta,
|
||||
openModal,
|
||||
savedChallenges,
|
||||
data: {
|
||||
challengeNode: {
|
||||
challenge: {
|
||||
@@ -273,7 +277,13 @@ class ShowClassic extends Component<ShowClassicProps, ShowClassicState> {
|
||||
}
|
||||
} = this.props;
|
||||
initConsole('');
|
||||
createFiles(challengeFiles ?? []);
|
||||
|
||||
const savedChallenge = savedChallenges?.find(challenge => {
|
||||
return challenge.id === challengeMeta.id;
|
||||
});
|
||||
|
||||
createFiles(savedChallenge?.challengeFiles || challengeFiles || []);
|
||||
|
||||
initTests(tests);
|
||||
if (showProjectPreview) openModal('projectPreview');
|
||||
updateChallengeMeta({
|
||||
@@ -521,6 +531,7 @@ export const query = graphql`
|
||||
block
|
||||
title
|
||||
description
|
||||
id
|
||||
hasEditableBoundaries
|
||||
instructions
|
||||
notes
|
||||
|
@@ -7,25 +7,43 @@ import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { connect } from 'react-redux';
|
||||
import { bindActionCreators, Dispatch } from 'redux';
|
||||
import { createSelector } from 'reselect';
|
||||
import { challengeTypes } from '../../../../utils/challenge-types';
|
||||
|
||||
import './tool-panel.css';
|
||||
import { openModal, executeChallenge } from '../redux';
|
||||
import { openModal, executeChallenge, challengeMetaSelector } from '../redux';
|
||||
|
||||
const mapStateToProps = () => ({});
|
||||
import { saveChallenge, isSignedInSelector } from '../../../redux';
|
||||
|
||||
const mapStateToProps = createSelector(
|
||||
challengeMetaSelector,
|
||||
isSignedInSelector,
|
||||
(
|
||||
{ challengeType }: { challengeId: string; challengeType: number },
|
||||
isSignedIn
|
||||
) => ({
|
||||
challengeType,
|
||||
isSignedIn
|
||||
})
|
||||
);
|
||||
const mapDispatchToProps = (dispatch: Dispatch) =>
|
||||
bindActionCreators(
|
||||
{
|
||||
executeChallenge,
|
||||
openHelpModal: () => openModal('help'),
|
||||
openVideoModal: () => openModal('video'),
|
||||
openResetModal: () => openModal('reset')
|
||||
openResetModal: () => openModal('reset'),
|
||||
saveChallenge
|
||||
},
|
||||
dispatch
|
||||
);
|
||||
|
||||
interface ToolPanelProps {
|
||||
challengeType: number;
|
||||
executeChallenge: (options?: { showCompletionModal: boolean }) => void;
|
||||
saveChallenge: () => void;
|
||||
isMobile?: boolean;
|
||||
isSignedIn: boolean;
|
||||
openHelpModal: () => void;
|
||||
openVideoModal: () => void;
|
||||
openResetModal: () => void;
|
||||
@@ -34,8 +52,11 @@ interface ToolPanelProps {
|
||||
}
|
||||
|
||||
function ToolPanel({
|
||||
challengeType,
|
||||
executeChallenge,
|
||||
saveChallenge,
|
||||
isMobile,
|
||||
isSignedIn,
|
||||
openHelpModal,
|
||||
openVideoModal,
|
||||
openResetModal,
|
||||
@@ -60,14 +81,26 @@ function ToolPanel({
|
||||
>
|
||||
{isMobile ? t('buttons.run') : t('buttons.run-test')}
|
||||
</Button>
|
||||
<Button
|
||||
block={true}
|
||||
bsStyle='primary'
|
||||
className='btn-invert'
|
||||
onClick={openResetModal}
|
||||
>
|
||||
{isMobile ? t('buttons.reset') : t('buttons.reset-code')}
|
||||
</Button>
|
||||
{isSignedIn && challengeType === challengeTypes.multiFileCertProject && (
|
||||
<Button
|
||||
block={true}
|
||||
bsStyle='primary'
|
||||
className='btn-invert'
|
||||
onClick={saveChallenge}
|
||||
>
|
||||
{isMobile ? t('buttons.save') : t('buttons.save-code')}
|
||||
</Button>
|
||||
)}
|
||||
{challengeType !== challengeTypes.multiFileCertProject && (
|
||||
<Button
|
||||
block={true}
|
||||
bsStyle='primary'
|
||||
className='btn-invert'
|
||||
onClick={openResetModal}
|
||||
>
|
||||
{isMobile ? t('buttons.reset') : t('buttons.reset-code')}
|
||||
</Button>
|
||||
)}
|
||||
<DropdownButton
|
||||
block={true}
|
||||
bsStyle='primary'
|
||||
|
@@ -21,6 +21,8 @@ import {
|
||||
} from '../../../redux';
|
||||
|
||||
import postUpdate$ from '../utils/postUpdate$';
|
||||
import { mapFilesToChallengeFiles } from '../../../utils/ajax';
|
||||
import { standardizeRequestBody } from '../../../utils/challenge-request-helpers';
|
||||
import { actionTypes } from './action-types';
|
||||
import {
|
||||
projectFormValuesSelector,
|
||||
@@ -34,7 +36,7 @@ import {
|
||||
function postChallenge(update, username) {
|
||||
const saveChallenge = postUpdate$(update).pipe(
|
||||
retry(3),
|
||||
switchMap(({ points }) => {
|
||||
switchMap(({ points, savedChallenges }) => {
|
||||
// TODO: do this all in ajax.ts
|
||||
const payloadWithClientProperties = {
|
||||
...omit(update.payload, ['files'])
|
||||
@@ -49,9 +51,12 @@ function postChallenge(update, username) {
|
||||
}
|
||||
return of(
|
||||
submitComplete({
|
||||
username,
|
||||
points,
|
||||
...payloadWithClientProperties
|
||||
submittedChallenge: {
|
||||
username,
|
||||
points,
|
||||
...payloadWithClientProperties
|
||||
},
|
||||
savedChallenges: mapFilesToChallengeFiles(savedChallenges)
|
||||
}),
|
||||
updateComplete()
|
||||
);
|
||||
@@ -76,24 +81,23 @@ function submitModern(type, state) {
|
||||
const { id, block } = challengeMetaSelector(state);
|
||||
const challengeFiles = challengeFilesSelector(state);
|
||||
const { username } = userSelector(state);
|
||||
const challengeInfo = {
|
||||
id,
|
||||
challengeType
|
||||
};
|
||||
|
||||
// Only send files to server, if it is a JS project or multiFile cert project
|
||||
let body;
|
||||
if (
|
||||
block === 'javascript-algorithms-and-data-structures-projects' ||
|
||||
challengeType === challengeTypes.multiFileCertProject
|
||||
) {
|
||||
challengeInfo.files = challengeFiles.reduce(
|
||||
(acc, { fileKey, ...curr }) => [...acc, { ...curr, key: fileKey }],
|
||||
[]
|
||||
);
|
||||
body = standardizeRequestBody({ id, challengeType, challengeFiles });
|
||||
} else {
|
||||
body = {
|
||||
id,
|
||||
challengeType
|
||||
};
|
||||
}
|
||||
|
||||
const update = {
|
||||
endpoint: '/modern-challenge-completed',
|
||||
payload: challengeInfo
|
||||
payload: body
|
||||
};
|
||||
return postChallenge(update, username);
|
||||
}
|
||||
|
@@ -25,6 +25,15 @@ import {
|
||||
isJavaScriptChallenge,
|
||||
isLoopProtected
|
||||
} from '../utils/build';
|
||||
import { challengeTypes } from '../../../../utils/challenge-types';
|
||||
import { createFlashMessage } from '../../../components/Flash/redux';
|
||||
import { FlashMessages } from '../../../components/Flash/redux/flash-messages';
|
||||
import {
|
||||
standardizeRequestBody,
|
||||
getStringSizeInBytes,
|
||||
bodySizeFits,
|
||||
MAX_BODY_SIZE
|
||||
} from '../../../utils/challenge-request-helpers';
|
||||
import { actionTypes } from './action-types';
|
||||
import {
|
||||
challengeDataSelector,
|
||||
@@ -45,7 +54,27 @@ import {
|
||||
const previewTimeout = 2500;
|
||||
let previewTask;
|
||||
|
||||
// when 'run tests' is clicked, do this first
|
||||
export function* executeCancellableChallengeSaga(payload) {
|
||||
const { challengeType, id } = yield select(challengeMetaSelector);
|
||||
const { challengeFiles } = yield select(challengeDataSelector);
|
||||
|
||||
// if multiFileCertProject, see if body/code size is submittable
|
||||
if (challengeType === challengeTypes.multiFileCertProject) {
|
||||
const body = standardizeRequestBody({ id, challengeFiles, challengeType });
|
||||
const bodySizeInBytes = getStringSizeInBytes(body);
|
||||
|
||||
if (!bodySizeFits(bodySizeInBytes)) {
|
||||
return yield put(
|
||||
createFlashMessage({
|
||||
type: 'danger',
|
||||
message: FlashMessages.ChallengeSubmitTooBig,
|
||||
variables: { 'max-size': MAX_BODY_SIZE, 'user-size': bodySizeInBytes }
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (previewTask) {
|
||||
yield cancel(previewTask);
|
||||
}
|
||||
|
@@ -68,7 +68,7 @@ export const createFiles = createAction(
|
||||
challengeFile.editableRegionBoundaries
|
||||
),
|
||||
seedEditableRegionBoundaries:
|
||||
challengeFile.editableRegionBoundaries.slice()
|
||||
challengeFile.editableRegionBoundaries?.slice()
|
||||
}))
|
||||
);
|
||||
|
||||
|
@@ -149,16 +149,19 @@ export function buildDOMChallenge(
|
||||
const finalFiles = challengeFiles.map(pipeLine);
|
||||
return Promise.all(finalFiles)
|
||||
.then(checkFilesErrors)
|
||||
.then(challengeFiles => ({
|
||||
challengeType: challengeTypes.html,
|
||||
build: concatHtml({
|
||||
required: finalRequires,
|
||||
template,
|
||||
challengeFiles
|
||||
}),
|
||||
sources: buildSourceMap(challengeFiles),
|
||||
loadEnzyme
|
||||
}));
|
||||
.then(challengeFiles => {
|
||||
return {
|
||||
challengeType:
|
||||
challengeTypes.html || challengeTypes.multiFileCertProject,
|
||||
build: concatHtml({
|
||||
required: finalRequires,
|
||||
template,
|
||||
challengeFiles
|
||||
}),
|
||||
sources: buildSourceMap(challengeFiles),
|
||||
loadEnzyme
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function buildJSChallenge({ challengeFiles }, options) {
|
||||
|
@@ -127,7 +127,8 @@ export class Block extends Component<BlockProps> {
|
||||
challenge.challengeType === 4 ||
|
||||
challenge.challengeType === 10 ||
|
||||
challenge.challengeType === 12 ||
|
||||
challenge.challengeType === 13;
|
||||
challenge.challengeType === 13 ||
|
||||
challenge.challengeType === 14;
|
||||
|
||||
const isTakeHomeProject = blockDashedName === 'take-home-projects';
|
||||
|
||||
|
@@ -3,7 +3,10 @@ import envData from '../../../config/env.json';
|
||||
|
||||
import type {
|
||||
ChallengeFile,
|
||||
ChallengeFiles,
|
||||
CompletedChallenge,
|
||||
SavedChallenge,
|
||||
SavedChallengeFile,
|
||||
User
|
||||
} from '../redux/prop-types';
|
||||
|
||||
@@ -65,15 +68,23 @@ interface SessionUser {
|
||||
sessionMeta: { activeDonations: number };
|
||||
}
|
||||
|
||||
type ChallengeFilesForFiles = {
|
||||
type CompleteChallengeFromApi = {
|
||||
files: Array<Omit<ChallengeFile, 'fileKey'> & { key: string }>;
|
||||
} & Omit<CompletedChallenge, 'challengeFiles'>;
|
||||
|
||||
type SavedChallengeFromApi = {
|
||||
files: Array<Omit<SavedChallengeFile, 'fileKey'> & { key: string }>;
|
||||
} & Omit<SavedChallenge, 'challengeFiles'>;
|
||||
|
||||
type ApiSessionResponse = Omit<SessionUser, 'user'>;
|
||||
type ApiUser = {
|
||||
user: {
|
||||
[username: string]: Omit<User, 'completedChallenges'> & {
|
||||
completedChallenges?: ChallengeFilesForFiles[];
|
||||
[username: string]: Omit<
|
||||
User,
|
||||
'completedChallenges' & 'savedChallenges'
|
||||
> & {
|
||||
completedChallenges?: CompleteChallengeFromApi[];
|
||||
savedChallenges?: SavedChallengeFromApi[];
|
||||
};
|
||||
};
|
||||
result?: string;
|
||||
@@ -87,30 +98,36 @@ type UserResponse = {
|
||||
function parseApiResponseToClientUser(data: ApiUser): UserResponse {
|
||||
const userData = data.user?.[data?.result ?? ''];
|
||||
let completedChallenges: CompletedChallenge[] = [];
|
||||
let savedChallenges: SavedChallenge[] = [];
|
||||
if (userData) {
|
||||
completedChallenges =
|
||||
userData.completedChallenges?.reduce(
|
||||
(acc: CompletedChallenge[], curr: ChallengeFilesForFiles) => {
|
||||
return [
|
||||
...acc,
|
||||
{
|
||||
...curr,
|
||||
challengeFiles: curr.files.map(({ key: fileKey, ...file }) => ({
|
||||
...file,
|
||||
fileKey
|
||||
}))
|
||||
}
|
||||
];
|
||||
},
|
||||
[]
|
||||
) ?? [];
|
||||
completedChallenges = mapFilesToChallengeFiles(
|
||||
userData.completedChallenges
|
||||
);
|
||||
savedChallenges = mapFilesToChallengeFiles(userData.savedChallenges);
|
||||
}
|
||||
return {
|
||||
user: { [data.result ?? '']: { ...userData, completedChallenges } },
|
||||
user: {
|
||||
[data.result ?? '']: { ...userData, completedChallenges, savedChallenges }
|
||||
},
|
||||
result: data.result
|
||||
};
|
||||
}
|
||||
|
||||
export function mapFilesToChallengeFiles<File, Rest>(
|
||||
fileContainer: ({ files: (File & { key: string })[] } & Rest)[] = []
|
||||
) {
|
||||
return fileContainer.map(({ files, ...rest }) => ({
|
||||
...rest,
|
||||
challengeFiles: mapKeyToFileKey(files)
|
||||
}));
|
||||
}
|
||||
|
||||
function mapKeyToFileKey<K>(
|
||||
files: (K & { key: string })[]
|
||||
): (Omit<K, 'key'> & { fileKey: string })[] {
|
||||
return files.map(({ key, ...rest }) => ({ ...rest, fileKey: key }));
|
||||
}
|
||||
|
||||
export function getSessionUser(): Promise<SessionUser> {
|
||||
const response: Promise<ApiUser & ApiSessionResponse> = get(
|
||||
'/user/get-session-user'
|
||||
@@ -207,6 +224,13 @@ export function postUserToken(): Promise<void> {
|
||||
return post('/user/user-token', {});
|
||||
}
|
||||
|
||||
export function postSaveChallenge(body: {
|
||||
id: string;
|
||||
files: ChallengeFiles;
|
||||
}): Promise<void> {
|
||||
return post('/save-challenge', body);
|
||||
}
|
||||
|
||||
/** PUT **/
|
||||
|
||||
interface MyAbout {
|
||||
|
44
client/src/utils/challenge-request-helpers.ts
Normal file
44
client/src/utils/challenge-request-helpers.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { ChallengeFiles } from '../redux/prop-types';
|
||||
|
||||
/*
|
||||
* Express's body-parser has a default size limit of 102400 bytes for a request body.
|
||||
* These helper functions make sure the request body isn't too big when saving or submitting multiFile cert projects
|
||||
*/
|
||||
|
||||
export const MAX_BODY_SIZE = 102400;
|
||||
|
||||
interface StandardizeRequestBodyArgs {
|
||||
id: string;
|
||||
challengeFiles: ChallengeFiles;
|
||||
challengeType: number;
|
||||
}
|
||||
|
||||
export function standardizeRequestBody({
|
||||
id,
|
||||
challengeFiles = [],
|
||||
challengeType
|
||||
}: StandardizeRequestBodyArgs) {
|
||||
return {
|
||||
id,
|
||||
files: challengeFiles?.map(({ fileKey, contents, ext, name, history }) => {
|
||||
return {
|
||||
contents,
|
||||
ext,
|
||||
history,
|
||||
key: fileKey,
|
||||
name
|
||||
};
|
||||
}),
|
||||
challengeType
|
||||
};
|
||||
}
|
||||
|
||||
export function getStringSizeInBytes(str = '') {
|
||||
const stringSizeInBytes = new Blob([JSON.stringify(str)]).size;
|
||||
|
||||
return stringSizeInBytes;
|
||||
}
|
||||
|
||||
export function bodySizeFits(bodySizeInBytes: number) {
|
||||
return bodySizeInBytes <= MAX_BODY_SIZE;
|
||||
}
|
@@ -20,6 +20,10 @@ const toneUrls = {
|
||||
'https://campfire-mode.freecodecamp.org/cert.mp3',
|
||||
[FlashMessages.CertificateMissing]: TRY_AGAIN,
|
||||
[FlashMessages.CertsPrivate]: TRY_AGAIN,
|
||||
[FlashMessages.ChallengeSaveTooBig]: TRY_AGAIN,
|
||||
[FlashMessages.ChallengeSubmitTooBig]: TRY_AGAIN,
|
||||
[FlashMessages.CodeSaved]: CHAL_COMP,
|
||||
[FlashMessages.CodeSaveError]: TRY_AGAIN,
|
||||
[FlashMessages.CompleteProjectFirst]: TRY_AGAIN,
|
||||
[FlashMessages.DeleteTokenErr]: TRY_AGAIN,
|
||||
[FlashMessages.EmailValid]: CHAL_COMP,
|
||||
|
Reference in New Issue
Block a user