Skip to content

Instantly share code, notes, and snippets.

@oscartbeaumont
Created November 17, 2022 06:44
Show Gist options
  • Select an option

  • Save oscartbeaumont/c197cbe6116a5b4bc9caee15774451a0 to your computer and use it in GitHub Desktop.

Select an option

Save oscartbeaumont/c197cbe6116a5b4bc9caee15774451a0 to your computer and use it in GitHub Desktop.
Lie to the compiler. Probally a bad idea.
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
use std::{ops::Deref, sync::Arc};
use rspc::Router as RspcRouter;
use worker::*;
mod utils {
use super::*;
use cfg_if::cfg_if;
cfg_if! {
// https://github.com/rustwasm/console_error_panic_hook#readme
if #[cfg(feature = "console_error_panic_hook")] {
extern crate console_error_panic_hook;
pub use self::console_error_panic_hook::set_once as set_panic_hook;
} else {
#[inline]
pub fn set_panic_hook() {}
}
}
pub fn log_request(req: &Request) {
console_log!(
"{} - [{}], located at: {:?}, within: {}",
Date::now().to_string(),
req.path(),
req.cf().coordinates().unwrap_or_default(),
req.cf().region().unwrap_or_else(|| "unknown region".into())
);
}
}
type App = RspcRouter<UnsafeEnv, ()>;
#[derive(Clone)]
pub struct UnsafeEnv(Arc<Env>);
// TODO: Here we are just lying to Rust. I don't know if this is a safe assumption to make but it seems to be working in my quick tests.
unsafe impl Send for UnsafeEnv {}
unsafe impl Sync for UnsafeEnv {}
impl Deref for UnsafeEnv {
type Target = Env;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
utils::set_panic_hook();
utils::log_request(&req);
let env = UnsafeEnv(Arc::new(env));
App::new()
.query("version", |t| {
t(move |env, _: ()| {
env.var("WORKERS_RS_VERSION")
.map(|v| v.to_string())
.unwrap() // TODO: Remove this?
})
})
.build()
.arced()
.endpoint(move || env)
.workers(req)
.await
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment