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

Use serde to more easily get query parameters #416

Merged
merged 1 commit into from
Nov 29, 2023
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions worker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ url = "2.4.0"
wasm-bindgen = "=0.2.87"
wasm-bindgen-futures = "0.4.36"
serde-wasm-bindgen = "0.6.1"
serde_urlencoded = "0.7"
wasm-streams = "0.3.0"
worker-kv = "0.6.0"
worker-macros = { path = "../worker-macros", version = "0.0.10" }
Expand Down
6 changes: 6 additions & 0 deletions worker/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ impl From<url::ParseError> for Error {
}
}

impl From<serde_urlencoded::de::Error> for Error {
fn from(e: serde_urlencoded::de::Error) -> Self {
Self::RustError(e.to_string())
}
}

impl From<serde_wasm_bindgen::Error> for Error {
fn from(e: serde_wasm_bindgen::Error) -> Self {
let val: JsValue = e.into();
Expand Down
9 changes: 9 additions & 0 deletions worker/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,15 @@ impl Request {
.map_err(|e| Error::RustError(format!("failed to parse Url from {e}: {url}")))
}

/// Deserialize the url query
pub fn query<Q: DeserializeOwned>(&self) -> Result<Q> {
let url = self.url()?;
let pairs = url.query_pairs();
let deserializer = serde_urlencoded::Deserializer::new(pairs);

Q::deserialize(deserializer).map_err(Error::from)
}

#[allow(clippy::should_implement_trait)]
pub fn clone(&self) -> Result<Self> {
self.edge_request
Expand Down
Loading