Renames and doc

This commit is contained in:
Malte Tammena 2021-10-24 14:54:18 +02:00
parent 36ee1832d9
commit 070208fb20
4 changed files with 19 additions and 14 deletions

12
src/cache/mod.rs vendored
View file

@ -32,7 +32,7 @@ use cacache::Metadata;
use chrono::{Duration, TimeZone};
use lazy_static::lazy_static;
use regex::Regex;
use reqwest::{blocking::Response, IntoUrl, StatusCode};
use reqwest::{blocking::Response, StatusCode, Url};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tracing::{info, warn};
@ -81,9 +81,9 @@ enum CacheResult<T> {
}
/// Wrapper around [`fetch`] for responses that contain json.
pub fn fetch_json<U, T>(url: U, local_ttl: Duration) -> Result<T>
pub fn fetch_json<S, T>(url: S, local_ttl: Duration) -> Result<T>
where
U: IntoUrl,
S: AsRef<str>,
T: DeserializeOwned,
{
fetch(url, local_ttl, |text, _| {
@ -93,14 +93,14 @@ where
}
/// Generic method for fetching remote url-based resources that may be cached.
pub fn fetch<Map, U, T>(url: U, local_ttl: Duration, map: Map) -> Result<T>
pub fn fetch<Map, S, T>(url: S, local_ttl: Duration, map: Map) -> Result<T>
where
U: IntoUrl,
S: AsRef<str>,
Map: FnOnce(String, Headers) -> Result<T>,
{
// Normalize the url at this point since we're using it
// as the cache key
let url = url.into_url().map_err(Error::Reqwest)?;
let url = Url::parse(url.as_ref()).map_err(|_| Error::InternalUrlError)?;
let url = url.as_ref();
info!("Fetching {:?}", url);
// Try getting the value from cache, if that fails, query the web

View file

@ -19,7 +19,7 @@ use crate::{
geoip, get_sane_terminal_dimensions,
meal::Meal,
pagination::PaginatedList,
print_json, ENDPOINT, TTL_CANTEENS, TTL_MEALS,
print_json, OPEN_MENSA_API, TTL_CANTEENS, TTL_MEALS,
};
use self::ser::CanteenCompleteWithoutMeals;
@ -62,7 +62,7 @@ pub struct Day {
impl Meta {
pub fn fetch(id: CanteenId) -> Result<Self> {
let url = format!("{}/canteens/{}", ENDPOINT, id);
let url = format!("{}/canteens/{}", OPEN_MENSA_API, id);
fetch_json(url, *TTL_CANTEENS)
}
}
@ -164,7 +164,7 @@ impl Canteen {
fn fetch_for_geo(geo: &GeoCommand, all: bool) -> Result<Vec<Self>> {
let url = if all {
info!("Fetching all canteens");
format!("{}/canteens", ENDPOINT)
format!("{}/canteens", OPEN_MENSA_API)
} else {
let (lat, long) = geoip::infer()?;
info!(
@ -173,7 +173,7 @@ impl Canteen {
);
format!(
"{}/canteens?near[lat]={}&near[lng]={}&near[dist]={}",
ENDPOINT, lat, long, geo.radius,
OPEN_MENSA_API, lat, long, geo.radius,
)
};
PaginatedList::new(url, *TTL_CANTEENS).consume()
@ -181,7 +181,7 @@ impl Canteen {
}
fn fetch_dates_for_canteen(id: CanteenId) -> Result<HashMap<NaiveDate, Fetchable<Vec<Meal>>>> {
let url = format!("{}/canteens/{}/days", ENDPOINT, id,);
let url = format!("{}/canteens/{}/days", OPEN_MENSA_API, id,);
let days: Vec<Day> = PaginatedList::new(url, *TTL_MEALS).consume()?;
Ok(days
.into_iter()
@ -190,7 +190,7 @@ fn fetch_dates_for_canteen(id: CanteenId) -> Result<HashMap<NaiveDate, Fetchable
}
fn fetch_meals(id: CanteenId, date: &NaiveDate) -> Result<Vec<Meal>> {
let url = format!("{}/canteens/{}/days/{}/meals", ENDPOINT, id, date);
let url = format!("{}/canteens/{}/days/{}/meals", OPEN_MENSA_API, id, date);
PaginatedList::new(url, *TTL_MEALS).consume()
}

View file

@ -33,6 +33,8 @@ pub enum Error {
DecodingUtf8(#[source] std::string::FromUtf8Error),
#[error("invalid date encountered: {_0}")]
InvalidDate(#[source] chrono::ParseError),
#[error("internal url parsing error. This is probably a bug")]
InternalUrlError,
}
pub trait ResultExt<T> {

View file

@ -91,6 +91,9 @@ macro_rules! color {
};
}
/// Conditionally select one of two expressions.
///
/// The former will be used unless the `--plain` flag is specified.
macro_rules! if_plain {
($fancy:expr, $plain:expr) => {
if crate::config::CONF.args.plain {
@ -120,8 +123,7 @@ use crate::{
tag::Tag,
};
const ENDPOINT: &str = "https://openmensa.org/api/v2";
const MIN_TERM_WIDTH: usize = 20;
const OPEN_MENSA_API: &str = "https://openmensa.org/api/v2";
lazy_static! {
static ref DIR: ProjectDirs =
@ -164,6 +166,7 @@ fn real_main() -> Result<()> {
}
fn get_sane_terminal_dimensions() -> (usize, usize) {
const MIN_TERM_WIDTH: usize = 20;
terminal_size::terminal_size()
.map(|(w, h)| (w.0 as usize, h.0 as usize))
.map(|(w, h)| (w.max(MIN_TERM_WIDTH), h))