Skip to main content

worker/
hyperdrive.rs

1use wasm_bindgen::{JsCast, JsValue};
2use worker_sys::types::Hyperdrive as HyperdriveSys;
3
4use crate::EnvBinding;
5use crate::{socket::socket_options_to_js_value, Socket, SocketOptions};
6
7#[derive(Debug)]
8pub struct Hyperdrive(HyperdriveSys);
9
10unsafe impl Send for Hyperdrive {}
11unsafe impl Sync for Hyperdrive {}
12
13impl EnvBinding for Hyperdrive {
14    const TYPE_NAME: &'static str = "Hyperdrive";
15
16    fn get(val: JsValue) -> crate::Result<Self> {
17        if !val.is_object() {
18            return Err("Binding cannot be cast to Hyperdrive from non-object value".into());
19        }
20
21        let has_connect = js_sys::Reflect::has(&val, &JsValue::from("connect"))?;
22        let has_connection_string = js_sys::Reflect::has(&val, &JsValue::from("connectionString"))?;
23        if !has_connect || !has_connection_string {
24            return Err("Binding cannot be cast to Hyperdrive: missing required methods/properties".into());
25        }
26
27        Ok(Self(val.unchecked_into()))
28    }
29}
30
31impl JsCast for Hyperdrive {
32    fn instanceof(val: &JsValue) -> bool {
33        val.is_instance_of::<HyperdriveSys>()
34    }
35
36    fn unchecked_from_js(val: JsValue) -> Self {
37        Self(val.into())
38    }
39
40    fn unchecked_from_js_ref(val: &JsValue) -> &Self {
41        unsafe { &*(val as *const JsValue as *const Self) }
42    }
43}
44
45impl AsRef<JsValue> for Hyperdrive {
46    fn as_ref(&self) -> &JsValue {
47        &self.0
48    }
49}
50
51impl From<Hyperdrive> for JsValue {
52    fn from(hyperdrive: Hyperdrive) -> Self {
53        JsValue::from(hyperdrive.0)
54    }
55}
56
57impl Hyperdrive {
58    pub fn connect(&self) -> crate::Result<Socket> {
59        self.connect_with_options(SocketOptions::default())
60    }
61
62    pub fn connect_with_options(&self, options: SocketOptions) -> crate::Result<Socket> {
63        let options = socket_options_to_js_value(&options);
64        let socket = self.0.connect(options)?;
65        Ok(Socket::from_inner(socket))
66    }
67
68    pub fn connection_string(&self) -> String {
69        self.0.connection_string()
70    }
71
72    pub fn host(&self) -> String {
73        self.0.host()
74    }
75
76    pub fn port(&self) -> u16 {
77        self.0.port()
78    }
79
80    pub fn user(&self) -> String {
81        self.0.user()
82    }
83
84    pub fn password(&self) -> String {
85        self.0.password()
86    }
87
88    pub fn database(&self) -> String {
89        self.0.database()
90    }
91}