diff --git a/src/fx.js b/src/fx.js index dae9d0c..7899b92 100644 --- a/src/fx.js +++ b/src/fx.js @@ -1 +1,13 @@ -// 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..eb44928 --- /dev/null +++ b/tests/fx.test.js @@ -0,0 +1,17 @@ +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(1000, 'EUR', 'EUR'), 1000); +}); + +test('convert caches rates between calls', async () => { + await convert(100, 'USD', 'JPY'); + const before = fetchCount(); + assert.equal(await convert(200, 'USD', 'JPY'), 30240); + assert.equal(fetchCount(), before); +});