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

Parse and populate route parameters #32

Merged
merged 4 commits into from
Jun 20, 2022
Merged
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
50 changes: 44 additions & 6 deletions src/route.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
use crate::{
healthcheck::HealthCheck,
request::{RequestParam, RequestParams},
request::{RequestParam, RequestParamType, RequestParams},
};
use async_trait::async_trait;
use derive_more::From;
use futures::future::{BoxFuture, Future, FutureExt};
use serde::Serialize;
use snafu::{OptionExt, Snafu};
use std::collections::HashMap;
use std::convert::Infallible;
use std::fmt::{self, Display, Formatter};
use std::marker::PhantomData;
use std::pin::Pin;
use std::str::FromStr;
use tide::{
http::{
self,
Expand All @@ -19,7 +22,6 @@ use tide::{
},
Body,
};
use tracing::info;

/// An error returned by a route handler.
///
Expand Down Expand Up @@ -163,6 +165,10 @@ pub struct Route<State, Error> {

#[derive(Clone, Debug, Snafu)]
pub enum RouteParseError {
MissingPathArray,
PathElementError,
InvalidTypeExpression,
UnrecognizedType,
MethodMustBeString,
InvalidMethod,
MissingPath,
Expand All @@ -174,9 +180,41 @@ pub enum RouteParseError {
impl<State, Error> Route<State, Error> {
/// Parse a [Route] from a TOML specification.
pub fn new(name: String, spec: &toml::Value) -> Result<Self, RouteParseError> {
// TODO this should be try_into...
info!("name: {}", name);
info!("spec: {:?}", spec);
let paths: Vec<String> = spec["PATH"]
.as_array()
.ok_or(RouteParseError::MissingPathArray)?
.iter()
.map(|v| {
v.as_str()
.ok_or(RouteParseError::PathElementError)
.unwrap()
.to_string()
})
.collect();
let mut pmap = HashMap::<String, RequestParam>::new();
for path in paths.iter() {
for seg in path.split('/') {
if seg.starts_with(':') {
let ptype = RequestParamType::from_str(
spec[seg]
.as_str()
.ok_or(RouteParseError::InvalidTypeExpression)?,
)
.map_err(|_| RouteParseError::UnrecognizedType)?;
// TODO Should the map key and name be different? If
// not, then RequestParam::name is redundant.
Comment on lines +204 to +205
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, RequestParam::name is probably redundant

pmap.insert(
seg.to_string(),
RequestParam {
name: seg.to_string(),
param_type: ptype,
// TODO How should we encode optioanl params?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking for now we would just check if the parameter appears in every pattern for the route. If so, it is "required".

I think later on, we should separate parameter declarations from route patterns, something like:

":my_param" = { type = "TaggedBase64", doc = "A parameter", optional = true }

and then allow parameters to be passed by URL segment, URL param, or request body.

required: true,
},
);
}
}
}
Ok(Route {
name,
patterns: match spec.get("PATH").context(MissingPathSnafu)? {
Expand Down Expand Up @@ -215,7 +253,7 @@ impl<State, Error> Route<State, Error> {
.context(MethodMustBeStringSnafu)?
.parse()
.map_err(|_| RouteParseError::InvalidMethod)?,
None => Method::Get,
None => http::Method::Get,
},
doc: String::new(),
handler: None,
Expand Down