-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
55 lines (48 loc) · 1.7 KB
/
Copy pathserver.ts
File metadata and controls
55 lines (48 loc) · 1.7 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
/**
* Runnable example: a small Hono app that uses both the @unirate/hono
* middleware and the ready-made router.
*
* Run with the Node adapter (any Hono runtime works):
*
* UNIRATE_API_KEY=your-key npx tsx examples/server.ts
*
* Then try:
* curl "http://localhost:3000/eur"
* 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 { Hono } from "hono";
import { serve } from "@hono/node-server";
import { unirate, unirateRouter } from "@unirate/hono";
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 Hono();
// 1. Middleware — a typed client is attached to c.var.unirate.
app.use(unirate({ apiKey }));
app.get("/eur", async (c) => {
const rate = await c.var.unirate.getRate("USD", "EUR");
return c.json({ pair: "USD/EUR", rate });
});
app.get("/summary", async (c) => {
const client = c.var.unirate;
const [rate, converted, currencies] = await Promise.all([
client.getRate("USD", "GBP"),
client.convert("EUR", 100, "USD"),
client.getSupportedCurrencies(),
]);
return c.json({
usdGbp: rate,
hundredUsdInEur: converted,
supportedCount: currencies.length,
});
});
// 2. Router — mount the ready-made JSON endpoints under /api/unirate.
app.route("/api/unirate", unirateRouter({ apiKey }));
const port = Number(process.env.PORT ?? 3000);
serve({ fetch: app.fetch, port });
console.log(`Listening on http://localhost:${port}`);