use crate::{errors::MyError, models::*}; use reqwest::Client; #[derive(Clone)] pub struct Supabase { pub url: String, pub key: String, pub client: Client, } impl Supabase { pub fn new(url: String, key: String) -> Self { Self { url, key, client: Client::new(), } } fn headers(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder { req.header("apikey", &self.key) .header("Authorization", format!("Bearer {}", self.key)) .header("Content-Type", "application/json") } pub async fn get_guest(&self, slug: &str) -> Result { let url = format!( "{}/rest/v1/guests?slug=eq.{}&select=name,slug,tempat&limit=1", self.url, slug ); let res = self .headers(self.client.get(url)) .send() .await? .json::>() .await?; res.into_iter().next().ok_or(MyError::NotFound) } pub async fn submit_rsvp(&self, form: RsvpRequest) -> Result { let url = format!("{}/rest/v1/guests?slug=eq.{}", self.url, form.slug); let res = self .headers(self.client.patch(url)) .header("Prefer", "return=representation") .json(&serde_json::json!({ "display": form.display, "attendance": form.attendance, "message": form.message, "pax": form.pax })) .send() .await? .json::>() .await?; res.into_iter().next().ok_or(MyError::NotFound) } pub async fn get_messages(&self) -> Result, MyError> { let url = format!( "{}/rest/v1/guests?message=not.is.null&select=display,attendance,message,updated_at&order=updated_at.desc", self.url ); let res = self .headers(self.client.get(url)) .send() .await? .json::>() .await?; Ok(res) } }