Skip to content

Instantly share code, notes, and snippets.

@tshemsedinov
Last active May 21, 2024 04:38
Show Gist options
  • Save tshemsedinov/20735f7f8b3c843c3dfa0bcd650e825b to your computer and use it in GitHub Desktop.
Save tshemsedinov/20735f7f8b3c843c3dfa0bcd650e825b to your computer and use it in GitHub Desktop.
Refactor this code using SRP
// Refactor this code using SRP (Single Responsibility Principle)
// To do this you need to decompose getRate into at least
// 2 functions: first will implement `retry` functionality,
// second will work with domain model (prepare call, get results)
// You may decompose to 3 functions or classes but please don't
// make over-engineering in Java style.
// Task from «Patterns for Async and Node.js»
// (Rethinking GRASP, SOLID, GoF for Frontend & Backend)
// 👉 https://t.me/asyncify
const API_EXCHANGE = {
host: 'openexchangerates.org',
path: 'api/latest.json?app_id=',
key: '1f43ea96b1e343fe94333dd2b97a109d',
};
const DEFAULT_RETRY = 3;
const getRate = async (currency, retry = DEFAULT_RETRY) => {
console.log({ currency, retry });
const { host, path, key } = API_EXCHANGE;
const url = `https://${host}/${path}${key}`;
const res = await fetch(url).catch(() => ({ ok: false }));
if (!res.ok) {
const attemptsLeft = retry - 1;
if (attemptsLeft > 0) return getRate(currency, retry - 1);
throw new Error('Can not get data');
}
const data = await res.json();
const rate = data.rates[currency];
return rate;
};
try {
const rate = await getRate('UAH');
console.log({ rate });
} catch (err) {
console.error({ err });
}
@tshemsedinov
Copy link
Author

Task from «Patterns for Async and Node.js»
👉 Rethinking GRASP, SOLID, GoF for Frontend & Backend

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment