worker/context.rs
1use std::future::Future;
2
3use crate::worker_sys::Context as JsContext;
4
5use wasm_bindgen::JsValue;
6use wasm_bindgen_futures::future_to_promise;
7
8/// A context bound to a `fetch` event.
9#[derive(Debug)]
10pub struct Context {
11 inner: JsContext,
12}
13
14unsafe impl Send for Context {}
15unsafe impl Sync for Context {}
16
17impl Context {
18 /// Constructs a context from an underlying JavaScript context object.
19 pub fn new(inner: JsContext) -> Self {
20 Self { inner }
21 }
22
23 /// Extends the lifetime of the "fetch" event which this context is bound to,
24 /// until the given future has been completed. The future is executed before the handler
25 /// terminates but does not block the response. For example, this is ideal for caching
26 /// responses or handling logging.
27 /// ```no_run
28 /// context.wait_until(async move {
29 /// let _ = cache.put(request, response).await;
30 /// });
31 /// ```
32 pub fn wait_until<F>(&self, future: F)
33 where
34 F: Future<Output = ()> + 'static,
35 {
36 self.inner
37 .wait_until(&future_to_promise(async {
38 future.await;
39 Ok(JsValue::UNDEFINED)
40 }))
41 .unwrap()
42 }
43
44 /// Prevents a runtime error response when the Worker script throws an unhandled exception.
45 /// Instead, the script will "fail open", which will proxy the request to the origin server
46 /// as though the Worker was never invoked.
47 pub fn pass_through_on_exception(&self) {
48 self.inner.pass_through_on_exception().unwrap()
49 }
50}
51
52impl AsRef<JsContext> for Context {
53 fn as_ref(&self) -> &JsContext {
54 &self.inner
55 }
56}