Skip to content

Commit

Permalink
Refine builder pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
kflansburg committed May 5, 2024
1 parent 5766930 commit 451fc7f
Show file tree
Hide file tree
Showing 6 changed files with 241 additions and 157 deletions.
25 changes: 11 additions & 14 deletions worker-sandbox/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::SomeSharedData;
use futures_util::stream::StreamExt;
use rand::Rng;
use std::time::Duration;
use worker::{console_log, Cache, Date, Delay, Env, Request, Response, Result};
use worker::{console_log, Cache, Date, Delay, Env, Request, Response, ResponseBuilder, Result};

fn key(req: &Request) -> Result<Option<String>> {
let uri = req.url()?;
Expand All @@ -24,12 +24,11 @@ pub async fn handle_cache_example(
Ok(resp)
} else {
console_log!("Cache MISS!");
let mut resp =
Response::from_json(&serde_json::json!({ "timestamp": Date::now().as_millis() }))?;

// Cache API respects Cache-Control headers. Setting s-max-age to 10
// will limit the response to be in cache for 10 seconds max
resp.headers_mut().set("cache-control", "s-maxage=10")?;
let mut resp = ResponseBuilder::new()
.with_header("cache-control", "s-maxage=10")?
.from_json(&serde_json::json!({ "timestamp": Date::now().as_millis() }))?;
cache.put(key, resp.cloned()?).await?;
Ok(resp)
}
Expand Down Expand Up @@ -60,13 +59,11 @@ pub async fn handle_cache_api_put(
) -> Result<Response> {
if let Some(key) = key(&req)? {
let cache = Cache::default();

let mut resp =
Response::from_json(&serde_json::json!({ "timestamp": Date::now().as_millis() }))?;

// Cache API respects Cache-Control headers. Setting s-max-age to 10
// will limit the response to be in cache for 10 seconds max
resp.headers_mut().set("cache-control", "s-maxage=10")?;
let mut resp = ResponseBuilder::new()
.with_header("cache-control", "s-maxage=10")?
.from_json(&serde_json::json!({ "timestamp": Date::now().as_millis() }))?;
cache.put(format!("https://{key}"), resp.cloned()?).await?;
return Ok(resp);
}
Expand Down Expand Up @@ -111,12 +108,12 @@ pub async fn handle_cache_stream(
Result::Ok(text.as_bytes().to_vec())
});

let mut resp = Response::from_stream(stream)?;
console_log!("resp = {:?}", resp);
// Cache API respects Cache-Control headers. Setting s-max-age to 10
// will limit the response to be in cache for 10 seconds max
resp.headers_mut().set("cache-control", "s-maxage=10")?;

let mut resp = ResponseBuilder::new()
.with_header("cache-control", "s-maxage=10")?
.from_stream(stream)?;
console_log!("resp = {:?}", resp);
cache.put(key, resp.cloned()?).await?;
Ok(resp)
}
Expand Down
6 changes: 3 additions & 3 deletions worker-sandbox/src/counter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ impl DurableObject for Counter {
.serialize_attachment("hello")
.expect("failed to serialize attachment");

return Ok(Response::empty()
.unwrap()
return Ok(ResponseBuilder::new()
.with_status(101)
.with_websocket(Some(pair.client)));
.with_websocket(pair.client)
.empty());
}

self.count += 10;
Expand Down
12 changes: 7 additions & 5 deletions worker-sandbox/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use futures_util::StreamExt;
use futures_util::TryStreamExt;
use std::time::Duration;
use worker::Env;
use worker::{console_log, Date, Delay, Request, Response, ResponseBody, Result};
use worker::{console_log, Date, Delay, Request, Response, ResponseBody, ResponseBuilder, Result};
pub fn handle_a_request(req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {
Response::ok(format!(
"req at: {}, located at: {:?}, within: {}",
Expand Down Expand Up @@ -60,7 +60,9 @@ pub async fn handle_headers(req: Request, _env: Env, _data: SomeSharedData) -> R
let mut headers: http::HeaderMap = req.headers().into();
headers.append("Hello", "World!".parse().unwrap());

Response::ok("returned your headers to you.").map(|res| res.with_headers(headers.into()))
ResponseBuilder::new()
.with_headers(headers.into())
.ok("returned your headers to you.")
}

#[worker::send]
Expand Down Expand Up @@ -133,9 +135,9 @@ pub async fn handle_status(req: Request, _env: Env, _data: SomeSharedData) -> Re
let code = segments.nth(1);
if let Some(code) = code {
return match code.parse::<u16>() {
Ok(status) => {
Response::ok("You set the status code!").map(|resp| resp.with_status(status))
}
Ok(status) => ResponseBuilder::new()
.with_status(status)
.ok("You set the status code!"),
Err(_e) => Response::error("Failed to parse your status code.", 400),
};
}
Expand Down
26 changes: 12 additions & 14 deletions worker-sandbox/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{
use std::convert::TryInto;
use std::sync::atomic::Ordering;

use worker::{console_log, Env, Fetch, Headers, Request, Response, Result};
use worker::{console_log, Env, Fetch, Request, Response, ResponseBuilder, Result};

#[cfg(not(feature = "http"))]
use worker::{RouteContext, Router};
Expand Down Expand Up @@ -348,19 +348,15 @@ pub fn make_router<'a>(data: SomeSharedData) -> Router<'a, SomeSharedData> {
}

fn respond(req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {
Response::ok(format!("Ok: {}", String::from(req.method()))).map(|resp| {
let mut headers = Headers::new();
headers.set("x-testing", "123").unwrap();
resp.with_headers(headers)
})
ResponseBuilder::new()
.with_header("x-testing", "123")?
.ok(format!("Ok: {}", String::from(req.method())))
}

async fn respond_async(req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {
Response::ok(format!("Ok (async): {}", String::from(req.method()))).map(|resp| {
let mut headers = Headers::new();
headers.set("x-testing", "123").unwrap();
resp.with_headers(headers)
})
ResponseBuilder::new()
.with_header("x-testing", "123")?
.ok(format!("Ok (async): {}", String::from(req.method())))
}

#[worker::send]
Expand All @@ -382,10 +378,12 @@ async fn catchall(req: Request, _env: Env, _data: SomeSharedData) -> Result<Resp
let path = uri.path();
console_log!("[or_else_any_method_async] caught: {}", path);

Fetch::Url("https://github.com/404".parse().unwrap())
let (builder, body) = Fetch::Url("https://github.com/404".parse().unwrap())
.send()
.await
.map(|resp| resp.with_status(404))
.await?
.into_parts();

Ok(builder.with_status(404).body(body))
}

async fn handle_options_catchall(
Expand Down
2 changes: 1 addition & 1 deletion worker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ pub use crate::queue::*;
pub use crate::r2::*;
pub use crate::request::{FromRequest, Request};
pub use crate::request_init::*;
pub use crate::response::{IntoResponse, Response, ResponseBody};
pub use crate::response::{IntoResponse, Response, ResponseBody, ResponseBuilder};
pub use crate::router::{RouteContext, RouteParams, Router};
pub use crate::schedule::*;
pub use crate::socket::*;
Expand Down
Loading

0 comments on commit 451fc7f

Please sign in to comment.