diff --git a/src/fx.js b/src/fx.js index dae9d0c..65bfb41 100644 --- a/src/fx.js +++ b/src/fx.js @@ -1 +1,17 @@ -// Currency conversion. (Not implemented yet.) +// Currency conversion. +import { SUPPORTED_CURRENCIES } from './config.js'; +import { roundCents } from './lib/money.js'; +import { cached } from './lib/ttl-cache.js'; +import { fetchRate } from './providers/fx-provider.js'; + +const RATE_TTL_MS = 10 * 60 * 1000; + +const cachedRate = cached(fetchRate, { ttlMs: RATE_TTL_MS }); + +export async function convert(amountCents, from, to) { + if (!SUPPORTED_CURRENCIES.includes(from)) throw new Error(`unsupported currency: ${from}`); + if (!SUPPORTED_CURRENCIES.includes(to)) throw new Error(`unsupported currency: ${to}`); + if (from === to) return amountCents; + const rate = await cachedRate(from, to); + return roundCents(amountCents * rate); +} diff --git a/src/index.js b/src/index.js index c7c695a..707ca81 100644 --- a/src/index.js +++ b/src/index.js @@ -1,4 +1,5 @@ export { categoryName } from './categories.js'; export { shippingCents } from './shipping.js'; export { vatRate } from './tax.js'; +export { convert } from './fx.js'; export { roundCents, formatCents } from './lib/money.js'; diff --git a/tests/fx.test.js b/tests/fx.test.js new file mode 100644 index 0000000..379cd3b --- /dev/null +++ b/tests/fx.test.js @@ -0,0 +1,30 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { convert } from '../src/fx.js'; +import { fetchCount, setRate } from '../src/providers/fx-provider.js'; + +test('convert rounds to whole cents', async () => { + assert.equal(await convert(1000, 'USD', 'EUR'), 920); + assert.equal(await convert(999, 'USD', 'GBP'), 789); + assert.equal(await convert(1000, 'USD', 'JPY'), 151200); +}); + +test('convert inverts a pair', async () => { + assert.equal(await convert(920, 'EUR', 'USD'), 1000); +}); + +test('convert to the same currency returns the amount', async () => { + assert.equal(await convert(1234, 'EUR', 'EUR'), 1234); +}); + +test('convert caches rates between calls', async () => { + setRate('GBP', 'EUR', 1.2); + const before = fetchCount(); + assert.equal(await convert(1000, 'GBP', 'EUR'), 1200); + assert.equal(await convert(500, 'GBP', 'EUR'), 600); + assert.equal(fetchCount() - before, 1); +}); + +test('convert rejects unsupported currencies', async () => { + await assert.rejects(convert(100, 'USD', 'XYZ'), /XYZ/); +});