Skip to content

Make translation service more resilient against bad implementations #1671

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions exercises/concept/translation-service/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ export class ExternalApi {
* @returns {Promise<Translation>}
*/
fetch(text) {
if (typeof text !== 'string') {
throw new BadRequest(
`Expected text when calling fetch(text), actual ${typeof text}.`
);
}

// Check if client is banned
if (mutex.current) {
return rejectWithRandomDelay(new AbusiveClientError());
Expand All @@ -60,6 +66,18 @@ export class ExternalApi {
* @param {(err?: Error) => void} callback
*/
request(text, callback) {
if (typeof text !== 'string') {
throw new BadRequest(
`Expected string text when calling request(text, callback), actual ${typeof text}.`
);
}

if (typeof callback !== 'function') {
throw new BadRequest(
`Expected callback function when calling fetch(text, callback), actual ${typeof callback}.`
);
}

if (this.values[text] && this.values[text][0]) {
mutex.current = true;
callback(new AbusiveClientError());
Expand Down Expand Up @@ -98,3 +116,9 @@ function rejectWithRandomDelay(value) {
function makeRandomError() {
return new Error(`Error code ${Math.ceil(Math.random() * 10000)}`);
}

class BadRequest extends Error {
constructor(message) {
super(message);
}
}