feat(client): ts-migrate client/src/utils (#42666)

* rename js files to ts

* start migrating ajax

* finish migrating ajax

* migrate algolia-locale-setup

* migrate format

* migrate format.test

* migrate get-words

* install axios for types in handled-error

* migrate handled-error

* migrate handled-error.test

* migrate report-error

* migrate script-loaders

* migrate to-learn-path

* correct renamed imports

* remove unnecessary type assertions in searchBar

* remove unnecessary global comment

* remove unnecessary max-len enable/disable

* change axios imports to type imports

* revert to .then() from await

* use UserType from redux/prop-types

* replace assertion with generic type

* revert format to JS

* remove unused getArticleById()

* update putUpdateUserFlag() to use Record

* remove unnecessary envData cast

* update algolia-locale-setup types

* remove invalid key property
This commit is contained in:
awu43
2021-07-12 02:17:58 -07:00
committed by GitHub
parent 92d7ae1725
commit e1d8f4be3a
27 changed files with 346 additions and 251 deletions

View File

@@ -150,6 +150,7 @@
"@types/store": "2.0.2", "@types/store": "2.0.2",
"@types/validator": "13.6.3", "@types/validator": "13.6.3",
"autoprefixer": "10.3.0", "autoprefixer": "10.3.0",
"axios": "^0.21.1",
"babel-plugin-transform-imports": "2.0.0", "babel-plugin-transform-imports": "2.0.0",
"chokidar": "3.5.2", "chokidar": "3.5.2",
"copy-webpack-plugin": "9.0.1", "copy-webpack-plugin": "9.0.1",

View File

@@ -22,8 +22,8 @@ import {
} from '../redux'; } from '../redux';
import { certMap } from '../resources/cert-and-project-map'; import { certMap } from '../resources/cert-and-project-map';
import { createFlashMessage } from '../components/Flash/redux'; import { createFlashMessage } from '../components/Flash/redux';
import standardErrorMessage from '../utils/standardErrorMessage'; import standardErrorMessage from '../utils/standard-error-message';
import reallyWeirdErrorMessage from '../utils/reallyWeirdErrorMessage'; import reallyWeirdErrorMessage from '../utils/really-weird-error-message';
import { langCodes } from '../../../config/i18n/all-langs'; import { langCodes } from '../../../config/i18n/all-langs';
import envData from '../../../config/env.json'; import envData from '../../../config/env.json';

View File

@@ -4,7 +4,7 @@ import React, { Component } from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { scriptLoader, scriptRemover } from '../../utils/scriptLoaders'; import { scriptLoader, scriptRemover } from '../../utils/script-loaders';
import { Loader } from '../../components/helpers'; import { Loader } from '../../components/helpers';
export class PayPalButtonScriptLoader extends Component { export class PayPalButtonScriptLoader extends Component {

View File

@@ -6,7 +6,7 @@ import { searchPageUrl } from '../../../utils/algolia-locale-setup';
const SearchBarOptimized = (): JSX.Element => { const SearchBarOptimized = (): JSX.Element => {
const { t } = useTranslation(); const { t } = useTranslation();
const placeholder = t('search.placeholder'); const placeholder = t('search.placeholder');
const searchUrl: string = searchPageUrl as string; const searchUrl = searchPageUrl;
const [value, setValue] = useState(''); const [value, setValue] = useState('');
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => const onChange = (event: React.ChangeEvent<HTMLInputElement>) =>
setValue(event.target.value); setValue(event.target.value);

View File

@@ -23,7 +23,7 @@ import SearchHits from './search-hits';
import './searchbar-base.css'; import './searchbar-base.css';
import './searchbar.css'; import './searchbar.css';
const searchUrl: string = searchPageUrl as string; const searchUrl = searchPageUrl;
const mapStateToProps = createSelector( const mapStateToProps = createSelector(
isSearchDropdownEnabledSelector, isSearchDropdownEnabledSelector,
isSearchBarFocusedSelector, isSearchBarFocusedSelector,

View File

@@ -7,7 +7,7 @@ import { searchPageUrl } from '../../../utils/algolia-locale-setup';
import Suggestion from './search-suggestion'; import Suggestion from './search-suggestion';
import NoHitsSuggestion from './no-hits-suggestion'; import NoHitsSuggestion from './no-hits-suggestion';
const searchUrl = searchPageUrl as string; const searchUrl = searchPageUrl;
interface customHitsPropTypes { interface customHitsPropTypes {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
hits: Array<any>; hits: Array<any>;

View File

@@ -5,7 +5,7 @@ import { isError } from 'lodash-es';
import { isHandledError, unwrapHandledError } from '../utils/handled-error'; import { isHandledError, unwrapHandledError } from '../utils/handled-error';
import { reportClientSideError } from '../utils/report-error'; import { reportClientSideError } from '../utils/report-error';
import { createFlashMessage } from '../components/Flash/redux'; import { createFlashMessage } from '../components/Flash/redux';
import reportedErrorMessage from '../utils/reportedErrorMessage'; import reportedErrorMessage from '../utils/reported-error-message';
const errorActionSelector = action => isError(action.payload); const errorActionSelector = action => isError(action.payload);

View File

@@ -5,7 +5,7 @@ import { updateMyEmailComplete, updateMyEmailError } from './';
import { createFlashMessage } from '../../components/Flash/redux'; import { createFlashMessage } from '../../components/Flash/redux';
import { putUserUpdateEmail } from '../../utils/ajax'; import { putUserUpdateEmail } from '../../utils/ajax';
import reallyWeirdErrorMessage from '../../utils/reallyWeirdErrorMessage'; import reallyWeirdErrorMessage from '../../utils/really-weird-error-message';
function* updateMyEmailSaga({ payload: email = '' }) { function* updateMyEmailSaga({ payload: email = '' }) {
if (!email || !isEmail(email)) { if (!email || !isEmail(email)) {

View File

@@ -10,7 +10,7 @@ import TestSuite from './Test-Suite';
import { challengeTestsSelector, isChallengeCompletedSelector } from '../redux'; import { challengeTestsSelector, isChallengeCompletedSelector } from '../redux';
import { createSelector } from 'reselect'; import { createSelector } from 'reselect';
import './side-panel.css'; import './side-panel.css';
import { mathJaxScriptLoader } from '../../../utils/scriptLoaders'; import { mathJaxScriptLoader } from '../../../utils/script-loaders';
const mapStateToProps = createSelector( const mapStateToProps = createSelector(
isChallengeCompletedSelector, isChallengeCompletedSelector,

View File

@@ -1,118 +0,0 @@
import envData from '../../../config/env.json';
import Tokens from 'csrf';
import cookies from 'browser-cookies';
const { apiLocation } = envData;
const base = apiLocation;
const tokens = new Tokens();
const defaultOptions = {
credentials: 'include'
};
// _csrf is passed to the client as a cookie. Tokens are sent back to the server
// via headers:
function getCSRFToken() {
const _csrf = typeof window !== 'undefined' && cookies.get('_csrf');
if (!_csrf) {
return '';
} else {
return tokens.create(_csrf);
}
}
function get(path) {
return fetch(`${base}${path}`, defaultOptions).then(res => res.json());
}
export function post(path, body) {
return request('POST', path, body);
}
function put(path, body) {
return request('PUT', path, body);
}
function request(method, path, body) {
const options = {
...defaultOptions,
method,
headers: {
'CSRF-Token': getCSRFToken(),
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
};
return fetch(`${base}${path}`, options).then(res => res.json());
}
/** GET **/
export function getSessionUser() {
return get('/user/get-session-user');
}
export function getUserProfile(username) {
return get(`/api/users/get-public-profile?username=${username}`);
}
export function getShowCert(username, certSlug) {
return get(`/certificate/showCert/${username}/${certSlug}`);
}
export function getUsernameExists(username) {
return get(`/api/users/exists?username=${username}`);
}
export function getArticleById(shortId) {
return get(`/n/${shortId}`);
}
/** POST **/
export function addDonation(body) {
return post('/donate/add-donation', body);
}
export function postReportUser(body) {
return post('/user/report-user', body);
}
export function postDeleteAccount(body) {
return post('/account/delete', body);
}
export function postResetProgress(body) {
return post('/account/reset-progress', body);
}
/** PUT **/
export function putUpdateMyAbout(values) {
return put('/update-my-about', { ...values });
}
export function putUpdateMyUsername(username) {
return put('/update-my-username', { username });
}
export function putUpdateMyProfileUI(profileUI) {
return put('/update-my-profileui', { profileUI });
}
export function putUpdateUserFlag(update) {
return put('/update-user-flag', update);
}
export function putUserAcceptsTerms(quincyEmails) {
return put('/update-privacy-terms', { quincyEmails });
}
export function putUserUpdateEmail(email) {
return put('/update-my-email', { email });
}
export function putVerifyCert(certSlug) {
return put('/certificate/verify', { certSlug });
}

160
client/src/utils/ajax.ts Normal file
View File

@@ -0,0 +1,160 @@
import envData from '../../../config/env.json';
import Tokens from 'csrf';
import cookies from 'browser-cookies';
import type { UserType } from '../redux/prop-types';
const { apiLocation } = envData;
const base = apiLocation;
const tokens = new Tokens();
const defaultOptions: RequestInit = {
credentials: 'include'
};
// _csrf is passed to the client as a cookie. Tokens are sent back to the server
// via headers:
function getCSRFToken() {
const _csrf = typeof window !== 'undefined' && cookies.get('_csrf');
if (!_csrf) {
return '';
} else {
return tokens.create(_csrf);
}
}
async function get<T>(path: string): Promise<T> {
return fetch(`${base}${path}`, defaultOptions).then<T>(res => res.json());
}
export function post<T = void>(path: string, body: unknown): Promise<T> {
return request('POST', path, body);
}
function put<T = void>(path: string, body: unknown): Promise<T> {
return request('PUT', path, body);
}
async function request<T>(
method: 'POST' | 'PUT',
path: string,
body: unknown
): Promise<T> {
const options: RequestInit = {
...defaultOptions,
method,
headers: {
'CSRF-Token': getCSRFToken(),
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
};
return fetch(`${base}${path}`, options).then<T>(res => res.json());
}
/** GET **/
interface SessionUser {
user: UserType;
sessionMeta: { activeDonations: number };
result: string;
}
export function getSessionUser(): Promise<SessionUser> {
return get('/user/get-session-user');
}
export function getUserProfile(username: string): Promise<UserType> {
return get(`/api/users/get-public-profile?username=${username}`);
}
interface Cert {
certTitle: string;
username: string;
date: Date;
completionTime: string;
}
export function getShowCert(username: string, certSlug: string): Promise<Cert> {
return get(`/certificate/showCert/${username}/${certSlug}`);
}
export function getUsernameExists(username: string): Promise<boolean> {
return get(`/api/users/exists?username=${username}`);
}
/** POST **/
interface Donation {
email: string;
amount: number;
duration: string;
provider: string;
subscriptionId: string;
customerId: string;
startDate: Date;
}
export function addDonation(body: Donation): Promise<void> {
return post('/donate/add-donation', body);
}
interface Report {
username: string;
reportDescription: string;
}
export function postReportUser(body: Report): Promise<void> {
return post('/user/report-user', body);
}
// Both are called without a payload in danger-zone-saga,
// which suggests both are sent without any body
// TODO: Convert to DELETE
export function postDeleteAccount(): Promise<void> {
return post('/account/delete', {});
}
export function postResetProgress(): Promise<void> {
return post('/account/reset-progress', {});
}
/** PUT **/
interface MyAbout {
name: string;
location: string;
about: string;
picture: string;
}
export function putUpdateMyAbout(values: MyAbout): Promise<void> {
return put('/update-my-about', { ...values });
}
export function putUpdateMyUsername(username: string): Promise<void> {
return put('/update-my-username', { username });
}
export function putUpdateMyProfileUI(
profileUI: UserType['profileUI']
): Promise<void> {
return put('/update-my-profileui', { profileUI });
}
// Update should contain only one flag and one new value
// It's possible to constrain to only one key with TS, but is overkill for this
// https://stackoverflow.com/a/60807986
export function putUpdateUserFlag(
update: Record<string, string>
): Promise<void> {
return put('/update-user-flag', update);
}
export function putUserAcceptsTerms(quincyEmails: boolean): Promise<void> {
return put('/update-privacy-terms', { quincyEmails });
}
export function putUserUpdateEmail(email: string): Promise<void> {
return put('/update-my-email', { email });
}
export function putVerifyCert(certSlug: string): Promise<void> {
return put('/certificate/verify', { certSlug });
}

View File

@@ -1,6 +1,8 @@
import envData from '../../../config/env.json'; import envData from '../../../config/env.json';
const { clientLocale } = envData; const { clientLocale } = envData as {
clientLocale: keyof typeof algoliaIndices;
};
const algoliaIndices = { const algoliaIndices = {
english: { english: {

View File

@@ -2,9 +2,7 @@ import __testHelpers, { removeJSComments } from './curriculum-helpers';
import jsTestValues from './__fixtures/curriculum-helpers-javascript'; import jsTestValues from './__fixtures/curriculum-helpers-javascript';
import cssTestValues from './__fixtures/curriculum-helpers-css'; import cssTestValues from './__fixtures/curriculum-helpers-css';
import htmlTestValues from './__fixtures/curriculum-helpers-html'; import htmlTestValues from './__fixtures/curriculum-helpers-html';
/* eslint-disable max-len */
import whiteSpaceTestValues from './__fixtures/curriculum-helpers-remove-white-space'; import whiteSpaceTestValues from './__fixtures/curriculum-helpers-remove-white-space';
/* eslint-enable max-len */
const { stringWithWhiteSpaceChars, stringWithWhiteSpaceCharsRemoved } = const { stringWithWhiteSpaceChars, stringWithWhiteSpaceCharsRemoved } =
whiteSpaceTestValues; whiteSpaceTestValues;

View File

@@ -1,12 +1,9 @@
/* global BigInt */ import { format } from './format';
const { format } = require('./format');
/* eslint-disable no-unused-vars */
function simpleFun() { function simpleFun() {
// eslint-disable-next-line no-var, @typescript-eslint/no-unused-vars
var x = 'y'; var x = 'y';
} }
/* eslint-enable no-unused-vars */
/* format uses util.inspect to do almost everything, the tests are just there /* format uses util.inspect to do almost everything, the tests are just there
to warn us if util.inspect ever changes */ to warn us if util.inspect ever changes */

View File

@@ -1,8 +1,18 @@
/* global preval */
// this lets us do dynamic work ahead of time, inlining motivation.json, so // this lets us do dynamic work ahead of time, inlining motivation.json, so
// that Webpack will never try to include locales that we know are not used. // that Webpack will never try to include locales that we know are not used.
interface Quote {
quote: string;
author: string;
}
interface Motivation {
compliments: string[];
motivationalQuotes: Quote[];
}
declare const preval: (s: TemplateStringsArray) => Motivation;
const words = preval` const words = preval`
const config = require('../../../config/env.json'); const config = require('../../../config/env.json');
const { clientLocale } = config; const { clientLocale } = config;
@@ -11,14 +21,14 @@ const words = preval`
module.exports = words; module.exports = words;
`; `;
function randomItem(arr) { function randomItem<T>(arr: T[]): T {
return arr[Math.floor(Math.random() * arr.length)]; return arr[Math.floor(Math.random() * arr.length)];
} }
export function randomQuote() { export function randomQuote(): Quote {
return randomItem(words.motivationalQuotes); return randomItem(words.motivationalQuotes);
} }
export function randomCompliment() { export function randomCompliment(): string {
return randomItem(words.compliments); return randomItem(words.compliments);
} }

View File

@@ -1,82 +0,0 @@
import { has } from 'lodash-es';
import standardErrorMessage from './standardErrorMessage';
import reportedErrorMessage from './reportedErrorMessage';
import { reportClientSideError } from './report-error';
export const handledErrorSymbol = Symbol('handledError');
export function isHandledError(err) {
return has(err, handledErrorSymbol);
}
export function unwrapHandledError(err) {
return handledErrorSymbol in err ? err[handledErrorSymbol] : {};
}
export function wrapHandledError(err, { type, message, redirectTo }) {
err[handledErrorSymbol] = { type, message, redirectTo };
return err;
}
export function handle400Error(e, options = { redirectTo: '/' }) {
const {
response: { status }
} = e;
let { redirectTo } = options;
let flash = { ...standardErrorMessage, redirectTo };
switch (status) {
case 401:
case 403: {
return {
...flash,
type: 'warn',
message: 'flash.not-authorized'
};
}
case 404: {
return {
...flash,
type: 'info',
message: 'flash.could-not-find'
};
}
default: {
return flash;
}
}
}
export function handle500Error(
e,
options = {
redirectTo: '/'
},
_reportClientSideError = reportClientSideError
) {
const { redirectTo } = options;
_reportClientSideError(e, 'We just handled a 5** error on the client');
return { ...reportedErrorMessage, redirectTo };
}
export function handleAPIError(
e,
options,
_reportClientSideError = reportClientSideError
) {
const { response: { status = 0 } = {} } = e;
if (status >= 400 && status < 500) {
return handle400Error(e, options);
}
if (status >= 500) {
return handle500Error(e, options, _reportClientSideError);
}
const { redirectTo } = options;
_reportClientSideError(
e,
'We just handled an api error on the client without an error status code'
);
return { ...reportedErrorMessage, redirectTo };
}

View File

@@ -1,4 +1,6 @@
import { isObject } from 'lodash-es'; import { isObject } from 'lodash-es';
import type { AxiosError } from 'axios';
import { import {
isHandledError, isHandledError,
wrapHandledError, wrapHandledError,
@@ -6,8 +8,9 @@ import {
handledErrorSymbol, handledErrorSymbol,
handleAPIError handleAPIError
} from './handled-error'; } from './handled-error';
import type { HandledError } from './handled-error';
import reportedErrorMessage from './reportedErrorMessage'; import reportedErrorMessage from './reported-error-message';
describe('client/src utilities', () => { describe('client/src utilities', () => {
describe('handled-error.js', () => { describe('handled-error.js', () => {
@@ -19,7 +22,7 @@ describe('client/src utilities', () => {
describe('isHandledError', () => { describe('isHandledError', () => {
it('returns a boolean', () => { it('returns a boolean', () => {
expect(typeof isHandledError({})).toEqual('boolean'); expect(typeof isHandledError({} as Error)).toEqual('boolean');
}); });
it('returns false for an unhandled error', () => { it('returns false for an unhandled error', () => {
@@ -27,7 +30,7 @@ describe('client/src utilities', () => {
}); });
it('returns true for a handled error', () => { it('returns true for a handled error', () => {
const handledError = new Error(); const handledError = new Error() as HandledError;
handledError[handledErrorSymbol] = {}; handledError[handledErrorSymbol] = {};
expect(isHandledError(handledError)).toEqual(true); expect(isHandledError(handledError)).toEqual(true);
@@ -39,14 +42,14 @@ describe('client/src utilities', () => {
// we need to make these tests more robust 💪 // we need to make these tests more robust 💪
it('returns an error with a handledError property', () => { it('returns an error with a handledError property', () => {
const handledError = wrapHandledError( const handledError = wrapHandledError(
new Error(), new Error() as HandledError,
mockHandledErrorData mockHandledErrorData
); );
expect(handledErrorSymbol in handledError).toEqual(true); expect(handledErrorSymbol in handledError).toEqual(true);
}); });
it('assigns error handling details to the handledError property', () => { it('assigns error handling details to the handledError property', () => {
const handledError = wrapHandledError( const handledError = wrapHandledError(
new Error(), new Error() as HandledError,
mockHandledErrorData mockHandledErrorData
); );
expect(handledError[handledErrorSymbol]).toEqual(mockHandledErrorData); expect(handledError[handledErrorSymbol]).toEqual(mockHandledErrorData);
@@ -57,13 +60,13 @@ describe('client/src utilities', () => {
// this is testing implementation details 👎 // this is testing implementation details 👎
// we need to make these tests more robust 💪 // we need to make these tests more robust 💪
it('returns an object by default', () => { it('returns an object by default', () => {
const error = new Error(); const error = new Error() as HandledError;
const unwrappedError = unwrapHandledError(error); const unwrappedError = unwrapHandledError(error);
expect(isObject(unwrappedError)).toBe(true); expect(isObject(unwrappedError)).toBe(true);
}); });
it('returns the data that was wrapped in the error', () => { it('returns the data that was wrapped in the error', () => {
const handledError = new Error(); const handledError = new Error() as HandledError;
handledError[handledErrorSymbol] = mockHandledErrorData; handledError[handledErrorSymbol] = mockHandledErrorData;
const unwrapped = unwrapHandledError(handledError); const unwrapped = unwrapHandledError(handledError);
expect(unwrapped).toEqual(mockHandledErrorData); expect(unwrapped).toEqual(mockHandledErrorData);
@@ -71,7 +74,7 @@ describe('client/src utilities', () => {
}); });
describe('handleAPIError', () => { describe('handleAPIError', () => {
let reportMock; let reportMock: () => void;
beforeEach(() => { beforeEach(() => {
reportMock = jest.fn(); reportMock = jest.fn();
}); });
@@ -82,7 +85,7 @@ describe('client/src utilities', () => {
response: { response: {
status: 400 status: 400
} }
}; } as AxiosError;
const result = handleAPIError( const result = handleAPIError(
axiosErrorMock, axiosErrorMock,
{ redirectTo: '/' }, { redirectTo: '/' },
@@ -100,7 +103,7 @@ describe('client/src utilities', () => {
response: { response: {
status: i status: i
} }
}; } as AxiosError;
handleAPIError(axiosErrorMock, { redirectTo: '/' }, reportMock); handleAPIError(axiosErrorMock, { redirectTo: '/' }, reportMock);
} }
expect(reportMock).not.toHaveBeenCalled(); expect(reportMock).not.toHaveBeenCalled();
@@ -111,7 +114,7 @@ describe('client/src utilities', () => {
response: { response: {
status: 502 status: 502
} }
}; } as AxiosError;
handleAPIError(axiosErrorMock, { redirectTo: '/' }, reportMock); handleAPIError(axiosErrorMock, { redirectTo: '/' }, reportMock);
expect(reportMock).toHaveBeenCalledTimes(1); expect(reportMock).toHaveBeenCalledTimes(1);
}); });
@@ -121,7 +124,7 @@ describe('client/src utilities', () => {
response: { response: {
status: 502 status: 502
} }
}; } as AxiosError;
const result = handleAPIError( const result = handleAPIError(
axiosErrorMock, axiosErrorMock,
{ redirectTo: '/' }, { redirectTo: '/' },
@@ -135,7 +138,7 @@ describe('client/src utilities', () => {
response: { response: {
status: 400 status: 400
} }
}; } as AxiosError;
const result = handleAPIError( const result = handleAPIError(
axiosErrorMock, axiosErrorMock,
{ redirectTo: null }, { redirectTo: null },

View File

@@ -0,0 +1,109 @@
import { has } from 'lodash-es';
import type { AxiosError, AxiosResponse } from 'axios';
import standardErrorMessage from './standard-error-message';
import reportedErrorMessage from './reported-error-message';
import { reportClientSideError } from './report-error';
interface ErrorData {
type?: string;
message?: string;
redirectTo?: string | null;
}
export const handledErrorSymbol = Symbol('handledError');
export type HandledError = Error & {
[handledErrorSymbol]: ErrorData;
};
export function isHandledError(err: unknown): err is HandledError {
return has(err, handledErrorSymbol);
}
export function unwrapHandledError(
err: HandledError
): ErrorData | Record<string, never> {
return handledErrorSymbol in err ? err[handledErrorSymbol] : {};
}
export function wrapHandledError(
err: Error,
{ type, message, redirectTo }: ErrorData
): HandledError {
(err as HandledError)[handledErrorSymbol] = {
type,
message,
redirectTo
};
return err as HandledError;
}
export function handle400Error(
e: AxiosError,
options: ErrorData = { redirectTo: '/' }
): ErrorData {
const { status } = e.response as AxiosResponse;
const { redirectTo } = options;
const flash = { ...standardErrorMessage, redirectTo };
switch (status) {
case 401:
case 403: {
return {
...flash,
type: 'warn',
message: 'flash.not-authorized'
};
}
case 404: {
return {
...flash,
type: 'info',
message: 'flash.could-not-find'
};
}
default: {
return flash;
}
}
}
export function handle500Error(
e: AxiosError,
options: ErrorData = {
redirectTo: '/'
},
_reportClientSideError: (
e: Error,
message: string
) => void = reportClientSideError
): ErrorData {
const { redirectTo } = options;
_reportClientSideError(e, 'We just handled a 5** error on the client');
return { ...reportedErrorMessage, redirectTo };
}
export function handleAPIError(
e: AxiosError,
options: ErrorData,
_reportClientSideError: (
e: Error,
message: string
) => void = reportClientSideError
): ErrorData {
const { response: { status = 0 } = {} } = e;
if (status >= 400 && status < 500) {
return handle400Error(e, options);
}
if (status >= 500) {
return handle500Error(e, options, _reportClientSideError);
}
const { redirectTo } = options;
_reportClientSideError(
e,
'We just handled an api error on the client without an error status code'
);
return { ...reportedErrorMessage, redirectTo };
}

View File

@@ -1,5 +1,3 @@
/* global describe it expect */
import { isChallenge, isLanding } from './path-parsers'; import { isChallenge, isLanding } from './path-parsers';
const pathnames = { const pathnames = {

View File

@@ -1,4 +0,0 @@
// TODO: integrate with Sentry?
export function reportClientSideError(e, message = 'Unhandled error') {
return console.error(`Client: ${message}`, e);
}

View File

@@ -0,0 +1,7 @@
// TODO: integrate with Sentry?
export function reportClientSideError(
e: Error,
message = 'Unhandled error'
): void {
return console.error(`Client: ${message}`, e);
}

View File

@@ -1,25 +1,29 @@
export const scriptLoader = (id, key, async, src, onload, text) => { export function scriptLoader(
let s = document.createElement('script'); id: string,
async: boolean,
src: string,
onload: (() => void) | null,
text: string
): void {
const s = document.createElement('script');
s.type = 'text/javascript'; s.type = 'text/javascript';
s.id = id; s.id = id;
s.key = key;
s.async = async; s.async = async;
s.onload = onload; s.onload = onload;
s.src = src; s.src = src;
s.text = text; s.text = text;
document.getElementsByTagName('head')[0].appendChild(s); document.getElementsByTagName('head')[0].appendChild(s);
}; }
export const scriptRemover = id => { export function scriptRemover(id: string): void {
let script = document.getElementById(id); const script = document.getElementById(id);
if (script) { if (script) {
script.remove(); script.remove();
} }
}; }
export const mathJaxScriptLoader = () => export function mathJaxScriptLoader(): void {
scriptLoader( scriptLoader(
'mathjax',
'mathjax', 'mathjax',
false, false,
'https://cdnjs.cloudflare.com/ajax/libs/mathjax/' + 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/' +
@@ -39,3 +43,4 @@ export const mathJaxScriptLoader = () =>
document.querySelector('.project-euler') document.querySelector('.project-euler')
]);` ]);`
); );
}

View File

@@ -1,6 +1,15 @@
import { withPrefix } from 'gatsby'; import { withPrefix } from 'gatsby';
export default function toLearnPath({ superBlock, block, challenge }) { interface ToLearnPathKwargs {
superBlock: string;
block: string;
challenge: string;
}
export default function toLearnPath({
superBlock,
block,
challenge
}: ToLearnPathKwargs): string {
let path = withPrefix('/learn'); let path = withPrefix('/learn');
if (superBlock) path += `/${superBlock}`; if (superBlock) path += `/${superBlock}`;
if (block) path += `/${block}`; if (block) path += `/${block}`;