-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
62 lines (56 loc) · 1.89 KB
/
Copy pathserver.ts
File metadata and controls
62 lines (56 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Runnable example: a small Koa app that uses both the @unirate/koa
* middleware and the ready-made router.
*
* Run it (needs koa, @koa/router, and a TS runner such as tsx):
*
* UNIRATE_API_KEY=your-key npx tsx examples/server.ts
*
* Then try:
* curl "http://localhost:3000/eur"
* curl "http://localhost:3000/summary"
* curl "http://localhost:3000/api/unirate/rate?from=USD&to=GBP"
* curl "http://localhost:3000/api/unirate/convert?from=USD&to=EUR&amount=100"
* curl "http://localhost:3000/api/unirate/currencies"
* curl "http://localhost:3000/api/unirate/vat?country=DE"
*/
import Koa from "koa";
import { unirate, unirateRouter } from "@unirate/koa";
const apiKey = process.env.UNIRATE_API_KEY;
if (!apiKey) {
console.error("Set UNIRATE_API_KEY (get a free key at https://unirateapi.com)");
process.exit(1);
}
const app = new Koa();
// 1. Middleware — a typed client is attached to ctx.state.unirate.
app.use(unirate({ apiKey }));
// 2. Router — mount the ready-made JSON endpoints under /api/unirate.
const router = unirateRouter({ apiKey });
router.prefix("/api/unirate");
app.use(router.routes()).use(router.allowedMethods());
// 3. Custom handlers using the client from ctx.state.
app.use(async (ctx) => {
if (ctx.path === "/eur") {
const rate = await ctx.state.unirate.getRate("USD", "EUR");
ctx.body = { pair: "USD/EUR", rate };
return;
}
if (ctx.path === "/summary") {
const client = ctx.state.unirate;
const [rate, converted, currencies] = await Promise.all([
client.getRate("USD", "GBP"),
client.convert("EUR", 100, "USD"),
client.getSupportedCurrencies(),
]);
ctx.body = {
usdGbp: rate,
hundredUsdInEur: converted,
supportedCount: currencies.length,
};
return;
}
});
const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => {
console.log(`Listening on http://localhost:${port}`);
});