Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a function to read an API from a file. #75

Merged
merged 1 commit into from
Aug 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions examples/hello-world/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use async_std::sync::RwLock;
use futures::FutureExt;
use serde::{Deserialize, Serialize};
use snafu::Snafu;
use std::fs;
use std::io;
use tide_disco::{http::StatusCode, Api, App, Error, RequestError};
use tracing::info;
Expand Down Expand Up @@ -37,10 +36,8 @@ async fn serve(port: u16) -> io::Result<()> {
let mut app = App::<_, HelloError>::with_state(RwLock::new("Hello".to_string()));
app.with_version(env!("CARGO_PKG_VERSION").parse().unwrap());

let mut api = Api::<RwLock<String>, HelloError>::new(toml::from_slice(&fs::read(
"examples/hello-world/api.toml",
)?)?)
.unwrap();
let mut api =
Api::<RwLock<String>, HelloError>::from_file("examples/hello-world/api.toml").unwrap();
api.with_version(env!("CARGO_PKG_VERSION").parse().unwrap());

// Can invoke by browsing
Expand Down
15 changes: 15 additions & 0 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ use serde_with::{serde_as, DisplayFromStr};
use snafu::{OptionExt, ResultExt, Snafu};
use std::collections::hash_map::{Entry, HashMap, IntoValues, Values};
use std::fmt::Display;
use std::fs;
use std::ops::Index;
use std::path::Path;
use tide::http::content::Accept;

/// An error encountered when parsing or constructing an [Api].
Expand All @@ -47,6 +49,7 @@ pub enum ApiError {
MissingFormatVersion,
InvalidFormatVersion,
AmbiguousRoutes { route1: String, route2: String },
CannotReadToml { reason: String },
}

/// Version information about an API.
Expand Down Expand Up @@ -178,6 +181,18 @@ impl<State, Error> Api<State, Error> {
})
}

/// Create an [Api] by reading a TOML specification from a file.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, ApiError> {
Self::new(
toml::from_slice(&fs::read(path).map_err(|err| ApiError::CannotReadToml {
reason: err.to_string(),
})?)
.map_err(|err| ApiError::CannotReadToml {
reason: err.to_string(),
})?,
)
}

/// Iterate over groups of routes with the same path.
pub fn routes_by_path(&self) -> impl Iterator<Item = (&str, RoutesWithPath<'_, State, Error>)> {
self.routes_by_path.iter().map(|(path, routes)| {
Expand Down