diff --git a/src/fx.js b/src/fx.js index dae9d0c..803d2ed 100644 --- a/src/fx.js +++ b/src/fx.js @@ -1 +1,19 @@ -// Currency conversion. (Not implemented yet.) +// Currency conversion. +import { fetchRate } from './providers/fx-provider.js'; +import { cached } from './lib/ttl-cache.js'; +import { roundCents } from './lib/money.js'; +import { SUPPORTED_CURRENCIES } from './config.js'; + +const RATE_TTL_MS = 10 * 60 * 1000; + +const getRate = cached(fetchRate, { ttlMs: RATE_TTL_MS }); + +export async function convert(amountCents, from, to) { + if (!Number.isInteger(amountCents)) throw new Error(`invalid amount: ${amountCents}`); + for (const currency of [from, to]) { + if (!SUPPORTED_CURRENCIES.includes(currency)) throw new Error(`unsupported currency: ${currency}`); + } + if (from === to) return amountCents; + const rate = await getRate(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..2edcf70 --- /dev/null +++ b/tests/fx.test.js @@ -0,0 +1,27 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { convert } from '../src/fx.js'; +import { fetchCount } from '../src/providers/fx-provider.js'; + +test('convert applies the rate and 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(920, 'EUR', 'USD'), 1000); +}); + +test('convert to the same currency returns the same amount', async () => { + assert.equal(await convert(1234, 'USD', 'USD'), 1234); +}); + +test('convert caches rates instead of calling the provider each time', async () => { + await convert(100, 'USD', 'JPY'); + const before = fetchCount(); + await convert(200, 'USD', 'JPY'); + await convert(300, 'USD', 'JPY'); + assert.equal(fetchCount(), before); +}); + +test('convert rejects bad input', async () => { + await assert.rejects(convert(1.5, 'USD', 'EUR'), /invalid amount/); + await assert.rejects(convert(100, 'USD', 'XYZ'), /unsupported currency: XYZ/); +});