diff --git a/src/fx.js b/src/fx.js index dae9d0c..b183ec0 100644 --- a/src/fx.js +++ b/src/fx.js @@ -1 +1,12 @@ -// 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'; + +const RATE_TTL_MS = 5 * 60 * 1000; +const getRate = cached(fetchRate, { ttlMs: RATE_TTL_MS }); + +export async function convert(amountCents, from, to) { + const rate = await getRate(from, to); + return roundCents(amountCents * rate); +} diff --git a/tests/fx.test.js b/tests/fx.test.js new file mode 100644 index 0000000..bb68f4f --- /dev/null +++ b/tests/fx.test.js @@ -0,0 +1,23 @@ +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 rounds to whole cents', async () => { + assert.equal(await convert(1000, 'USD', 'EUR'), 920); + assert.equal(await convert(999, 'USD', 'GBP'), 789); // 789.21 + assert.equal(await convert(0, 'USD', 'JPY'), 0); +}); + +test('convert uses the inverse rate and same-currency identity', async () => { + assert.equal(await convert(920, 'EUR', 'USD'), 1000); + assert.equal(await convert(1234, 'USD', 'USD'), 1234); +}); + +test('convert caches rates', async () => { + await convert(100, 'USD', 'JPY'); + const before = fetchCount(); + await convert(500, 'USD', 'JPY'); + await convert(700, 'USD', 'JPY'); + assert.equal(fetchCount(), before); +});