Skip to main content

unirate_rocket/
lib.rs

1//! # unirate-rocket
2//!
3//! [Rocket](https://rocket.rs) integration for the
4//! [UniRate API](https://unirateapi.com) — free, real-time currency exchange
5//! rates, conversion, and VAT rates.
6//!
7//! This crate exposes a ready-made set of routes via [`unirate_routes`] plus a
8//! [`UniRateFairing`] that manages a single [`unirate_api::Client`] in Rocket's
9//! state. Together they add four `GET` routes:
10//!
11//! | Route         | Query params            | Backing client call                              |
12//! |---------------|-------------------------|--------------------------------------------------|
13//! | `/rate`       | `from`, `to`            | [`Client::get_rate`] / [`Client::get_all_rates`] |
14//! | `/convert`    | `from`, `to`, `amount`  | [`Client::convert`]                              |
15//! | `/currencies` | —                       | [`Client::get_supported_currencies`]             |
16//! | `/vat`        | `country` (optional)    | [`Client::get_vat_rate`] / [`Client::get_vat_rates`] |
17//!
18//! UniRate errors are mapped to the matching HTTP status with a JSON error body
19//! via [`ApiError`], which implements Rocket's
20//! [`Responder`](rocket::response::Responder).
21//!
22//! ## Client sourcing
23//!
24//! The UniRate HTTP client itself is **not** re-implemented here — this crate
25//! depends on the published [`unirate-api`](https://crates.io/crates/unirate-api)
26//! crate (`unirate_api::Client`) and only adds the Rocket wiring. That keeps the
27//! client parity in one place and this crate small.
28//!
29//! ## Quick start
30//!
31//! ```no_run
32//! use rocket::launch;
33//! use unirate_rocket::{unirate_routes, UniRateFairing};
34//!
35//! #[launch]
36//! fn rocket() -> _ {
37//!     let key = std::env::var("UNIRATE_API_KEY").expect("UNIRATE_API_KEY");
38//!     rocket::build()
39//!         .attach(UniRateFairing::new(key))
40//!         .mount("/", unirate_routes())
41//! }
42//! ```
43//!
44//! The [`Client`] is managed by the [`UniRateFairing`], so the handlers read it
45//! from [`rocket::State<Client>`]. If you'd rather manage the client yourself,
46//! skip the fairing and call [`rocket::Rocket::manage`] with a [`Client`]:
47//!
48//! ```no_run
49//! use rocket::routes;
50//! use unirate_api::Client;
51//! use unirate_rocket::unirate_routes;
52//!
53//! let client = Client::new("your-api-key");
54//! let rocket = rocket::build()
55//!     .manage(client)
56//!     .mount("/currency", unirate_routes());
57//! // now GET /currency/rate, /currency/convert, ...
58//! ```
59
60#![deny(missing_debug_implementations)]
61#![warn(rust_2018_idioms)]
62
63use std::collections::HashMap;
64
65use rocket::fairing::{self, Fairing, Info, Kind};
66use rocket::http::{ContentType, Status};
67use rocket::request::Request;
68use rocket::response::{self, Responder, Response};
69use rocket::serde::json::Json;
70use rocket::{get, routes, Build, Rocket, State};
71use serde::Serialize;
72use serde_json::json;
73use unirate_api::{Client, UniRateError, VatRate, VatRateResponse, VatRatesResponse};
74
75/// Return the UniRate routes for mounting on a Rocket instance.
76///
77/// Mount them at any base path with [`rocket::Rocket::mount`]. The handlers read
78/// the [`Client`] from [`rocket::State`], so make sure a [`Client`] is managed —
79/// either by attaching [`UniRateFairing`] or by calling
80/// [`rocket::Rocket::manage`] yourself.
81///
82/// Routes:
83/// - `GET /rate?from=USD&to=EUR` — single rate. Omit `to` to get every rate for
84///   `from` as a `{ "rates": { .. } }` map.
85/// - `GET /convert?from=USD&to=EUR&amount=100` — converted amount.
86/// - `GET /currencies` — list of supported currency codes.
87/// - `GET /vat?country=DE` — VAT for one country. Omit `country` for all.
88pub fn unirate_routes() -> Vec<rocket::Route> {
89    routes![
90        rate_handler,
91        convert_handler,
92        currencies_handler,
93        vat_handler
94    ]
95}
96
97// ---------------------------------------------------------------------------
98// Fairing
99// ---------------------------------------------------------------------------
100
101/// A Rocket [`Fairing`] that manages a single [`unirate_api::Client`] in state.
102///
103/// Attach it to your Rocket instance so the [`unirate_routes`] handlers can read
104/// the client from [`rocket::State`]:
105///
106/// ```no_run
107/// use unirate_rocket::{unirate_routes, UniRateFairing};
108///
109/// let rocket = rocket::build()
110///     .attach(UniRateFairing::new(std::env::var("UNIRATE_API_KEY").unwrap()))
111///     .mount("/", unirate_routes());
112/// ```
113///
114/// If you already have a configured [`Client`] (custom base URL or timeout), use
115/// [`UniRateFairing::with_client`].
116#[derive(Debug)]
117pub struct UniRateFairing {
118    client: Client,
119}
120
121impl UniRateFairing {
122    /// Build a fairing that manages a [`Client`] created from `api_key`.
123    pub fn new(api_key: impl Into<String>) -> Self {
124        UniRateFairing {
125            client: Client::new(api_key),
126        }
127    }
128
129    /// Build a fairing around a pre-configured [`Client`].
130    ///
131    /// Use this when you need a custom base URL or timeout (via
132    /// [`Client::builder`]).
133    pub fn with_client(client: Client) -> Self {
134        UniRateFairing { client }
135    }
136}
137
138#[rocket::async_trait]
139impl Fairing for UniRateFairing {
140    fn info(&self) -> Info {
141        Info {
142            name: "UniRate Client",
143            kind: Kind::Ignite,
144        }
145    }
146
147    async fn on_ignite(&self, rocket: Rocket<Build>) -> fairing::Result {
148        // Clone the client into managed state. `unirate_api::Client` is cheaply
149        // cloneable (it wraps a connection-pooled reqwest client).
150        Ok(rocket.manage(self.client.clone()))
151    }
152}
153
154// ---------------------------------------------------------------------------
155// Handlers
156// ---------------------------------------------------------------------------
157
158/// `GET /rate?from=USD&to=EUR`
159///
160/// With `to`: returns `{ "from", "to", "rate" }`. Without `to`: returns
161/// `{ "from", "rates": { .. } }` for every rate of `from`. `from` defaults to
162/// `USD`.
163#[get("/rate?<from>&<to>")]
164async fn rate_handler(
165    client: &State<Client>,
166    from: Option<&str>,
167    to: Option<&str>,
168) -> Result<Json<serde_json::Value>, ApiError> {
169    let from = from.unwrap_or("USD");
170    match to {
171        Some(to) => {
172            let rate = client.get_rate(from, to).await?;
173            Ok(Json(json!({
174                "from": from.to_uppercase(),
175                "to": to.to_uppercase(),
176                "rate": rate,
177            })))
178        }
179        None => {
180            let rates: HashMap<String, f64> = client.get_all_rates(from).await?;
181            Ok(Json(json!({
182                "from": from.to_uppercase(),
183                "rates": rates,
184            })))
185        }
186    }
187}
188
189/// `GET /convert?from=USD&to=EUR&amount=100`
190///
191/// `to` is required (a missing `to` is a `422` from Rocket's query guard).
192/// `from` defaults to `USD`, `amount` defaults to `1`.
193#[get("/convert?<from>&<to>&<amount>")]
194async fn convert_handler(
195    client: &State<Client>,
196    from: Option<&str>,
197    to: &str,
198    amount: Option<f64>,
199) -> Result<Json<ConvertResponse>, ApiError> {
200    let from = from.unwrap_or("USD");
201    let amount = amount.unwrap_or(1.0);
202    let result = client.convert(amount, from, to).await?;
203    Ok(Json(ConvertResponse {
204        from: from.to_uppercase(),
205        to: to.to_uppercase(),
206        amount,
207        result,
208    }))
209}
210
211/// `GET /currencies` — list of supported currency codes.
212#[get("/currencies")]
213async fn currencies_handler(client: &State<Client>) -> Result<Json<CurrenciesResponse>, ApiError> {
214    let currencies = client.get_supported_currencies().await?;
215    Ok(Json(CurrenciesResponse { currencies }))
216}
217
218/// `GET /vat?country=DE` — VAT for one country. Omit `country` for all.
219#[get("/vat?<country>")]
220async fn vat_handler(
221    client: &State<Client>,
222    country: Option<&str>,
223) -> Result<Json<serde_json::Value>, ApiError> {
224    match country {
225        Some(country) => {
226            let resp = client.get_vat_rate(country).await?;
227            Ok(Json(json!(VatCountry::from(resp))))
228        }
229        None => {
230            let resp = client.get_vat_rates().await?;
231            Ok(Json(json!(VatAll::from(resp))))
232        }
233    }
234}
235
236// ---------------------------------------------------------------------------
237// Response bodies
238// ---------------------------------------------------------------------------
239
240/// Body of a successful `GET /convert`.
241#[derive(Debug, Serialize)]
242pub struct ConvertResponse {
243    /// Source currency (uppercased).
244    pub from: String,
245    /// Target currency (uppercased).
246    pub to: String,
247    /// The input amount.
248    pub amount: f64,
249    /// The converted amount.
250    pub result: f64,
251}
252
253/// Body of a successful `GET /currencies`.
254#[derive(Debug, Serialize)]
255pub struct CurrenciesResponse {
256    /// Supported currency codes.
257    pub currencies: Vec<String>,
258}
259
260/// VAT rate for a single country, as returned in a JSON response.
261///
262/// The `unirate-api` [`VatRate`] type only derives `Deserialize`, so this
263/// serializable mirror is used for the outgoing HTTP body.
264#[derive(Debug, Serialize)]
265pub struct VatRateBody {
266    /// ISO-3166 alpha-2 country code, when supplied by the upstream API.
267    #[serde(skip_serializing_if = "Option::is_none")]
268    pub country_code: Option<String>,
269    /// Human-readable country name, when supplied.
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub country_name: Option<String>,
272    /// VAT rate as a percentage (e.g. `19.0`).
273    pub vat_rate: f64,
274}
275
276impl From<VatRate> for VatRateBody {
277    fn from(v: VatRate) -> Self {
278        VatRateBody {
279            country_code: v.country_code,
280            country_name: v.country_name,
281            vat_rate: v.vat_rate,
282        }
283    }
284}
285
286/// Body of a successful `GET /vat?country=XX`.
287#[derive(Debug, Serialize)]
288pub struct VatCountry {
289    /// Echoed country code.
290    #[serde(skip_serializing_if = "Option::is_none")]
291    pub country: Option<String>,
292    /// The country's VAT detail.
293    pub vat_data: VatRateBody,
294}
295
296impl From<VatRateResponse> for VatCountry {
297    fn from(r: VatRateResponse) -> Self {
298        VatCountry {
299            country: r.country,
300            vat_data: r.vat_data.into(),
301        }
302    }
303}
304
305/// Body of a successful `GET /vat` (all countries).
306#[derive(Debug, Serialize)]
307pub struct VatAll {
308    /// Snapshot date, when provided.
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub date: Option<String>,
311    /// Number of countries in the response.
312    pub total_countries: u32,
313    /// Per-country VAT rates keyed by ISO-3166 alpha-2 code.
314    pub vat_rates: HashMap<String, VatRateBody>,
315}
316
317impl From<VatRatesResponse> for VatAll {
318    fn from(r: VatRatesResponse) -> Self {
319        VatAll {
320            date: r.date,
321            total_countries: r.total_countries,
322            vat_rates: r
323                .vat_rates
324                .into_iter()
325                .map(|(k, v)| (k, v.into()))
326                .collect(),
327        }
328    }
329}
330
331// ---------------------------------------------------------------------------
332// Error mapping
333// ---------------------------------------------------------------------------
334
335/// Wraps a [`UniRateError`] and turns it into an HTTP response via Rocket's
336/// [`Responder`].
337///
338/// The status code follows the UniRate error → HTTP mapping:
339///
340/// | UniRate error                    | HTTP status |
341/// |----------------------------------|-------------|
342/// | `InvalidDate`                    | 400 Bad Request |
343/// | `Authentication`                 | 401 Unauthorized |
344/// | `Api { status: 403, .. }`        | 403 Forbidden (Pro-gated) |
345/// | `InvalidCurrency`                | 404 Not Found |
346/// | `RateLimit`                      | 429 Too Many Requests |
347/// | `Api { status: 503, .. }`        | 503 Service Unavailable |
348/// | `Api { status, .. }` (other)     | that status |
349/// | `Http` / `Json` (transport)      | 502 Bad Gateway |
350#[derive(Debug)]
351pub struct ApiError(pub UniRateError);
352
353impl From<UniRateError> for ApiError {
354    fn from(err: UniRateError) -> Self {
355        ApiError(err)
356    }
357}
358
359impl std::fmt::Display for ApiError {
360    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361        self.0.fmt(f)
362    }
363}
364
365impl std::error::Error for ApiError {}
366
367impl ApiError {
368    /// Compute the outgoing (status, message) pair for this error.
369    fn parts(&self) -> (Status, String) {
370        match &self.0 {
371            UniRateError::InvalidDate => {
372                (Status::BadRequest, "Invalid request parameters".to_string())
373            }
374            UniRateError::Authentication => (
375                Status::Unauthorized,
376                "Missing or invalid API key".to_string(),
377            ),
378            UniRateError::InvalidCurrency => (
379                Status::NotFound,
380                "Currency not found or no data available".to_string(),
381            ),
382            UniRateError::RateLimit => (Status::TooManyRequests, "Rate limit exceeded".to_string()),
383            UniRateError::Api { status, body } => {
384                let code = Status::from_code(*status).unwrap_or(Status::BadGateway);
385                let message = match *status {
386                    403 => "Endpoint requires a Pro subscription".to_string(),
387                    503 => "Service unavailable".to_string(),
388                    _ if body.is_empty() => format!("Upstream API error (status {status})"),
389                    _ => body.clone(),
390                };
391                (code, message)
392            }
393            // Transport / decode failures are our side of the fence — the
394            // upstream call never completed cleanly, so surface a 502.
395            UniRateError::Http(_) | UniRateError::Json(_) => (
396                Status::BadGateway,
397                "Failed to reach the UniRate API".to_string(),
398            ),
399            // `UniRateError` is `#[non_exhaustive]`; be defensive.
400            _ => (Status::InternalServerError, "Unexpected error".to_string()),
401        }
402    }
403}
404
405impl<'r> Responder<'r, 'static> for ApiError {
406    fn respond_to(self, request: &'r Request<'_>) -> response::Result<'static> {
407        let (status, message) = self.parts();
408        let body = json!({
409            "error": {
410                "status": status.code,
411                "message": message,
412            }
413        })
414        .to_string();
415
416        Response::build_from(body.respond_to(request)?)
417            .status(status)
418            .header(ContentType::JSON)
419            .ok()
420    }
421}