bevy_postgrest/client.rs
1use bevy::ecs::system::Resource;
2use ehttp::Headers;
3
4use crate::builder::Builder;
5
6#[derive(Clone, Resource)]
7pub struct Client {
8 url: String,
9 schema: Option<String>,
10 headers: Headers,
11}
12
13impl Client {
14 /// Creates a Postgrest client.
15 ///
16 /// # Example
17 ///
18 /// ```
19 /// let client = Postgrest::new("http://your.postgrest.endpoint");
20 /// ```
21 pub fn new<T>(url: T) -> Self
22 where
23 T: Into<String>,
24 {
25 Client {
26 url: url.into(),
27 schema: None,
28 headers: Headers::new(&vec![]),
29 }
30 }
31
32 /// Switches the schema.
33 ///
34 /// # Note
35 ///
36 /// You can only switch schemas before you call `from` or `rpc`.
37 ///
38 /// # Example
39 ///
40 /// ```
41 /// let client = Postgrest::new("http://your.postgrest.endpoint");
42 /// client.schema("private");
43 /// ```
44 pub fn schema<T>(&mut self, schema: T) -> &mut Self
45 where
46 T: Into<String>,
47 {
48 self.schema = Some(schema.into());
49 self
50 }
51
52 /// Add arbitrary headers to the request. For instance when you may want to connect
53 /// through an API gateway that needs an API key header.
54 ///
55 /// # Example
56 ///
57 /// ```
58 /// let client = Postgrest::new("https://your.postgrest.endpoint")
59 /// .insert_header("apikey", "super.secret.key")
60 /// .from("table");
61 /// ```
62 pub fn insert_header(
63 &mut self,
64 header_name: impl ToString,
65 header_value: impl ToString,
66 ) -> &mut Self {
67 // TODO be safer with CSV / single value headers
68 self.headers.insert(header_name, header_value);
69 self
70 }
71
72 /// Perform a table operation.
73 ///
74 /// # Example
75 ///
76 /// ```
77 /// let client = Postgrest::new("http://your.postgrest.endpoint");
78 /// client.from("table");
79 /// ```
80 pub fn from<T>(&self, table: T) -> Builder
81 where
82 T: AsRef<str>,
83 {
84 let url = format!("{}/{}", self.url, table.as_ref());
85 Builder::new(url, self.schema.clone(), self.headers.clone())
86 }
87
88 /// Perform a stored procedure call.
89 ///
90 /// # Example
91 ///
92 /// ```
93 /// let client = Postgrest::new("http://your.postgrest.endpoint");
94 /// client.rpc("multiply", r#"{"a": 1, "b": 2}"#);
95 /// ```
96 pub fn rpc<T, U>(&self, function: T, params: U) -> Builder
97 where
98 T: AsRef<str>,
99 U: Into<String>,
100 {
101 let url = format!("{}/rpc/{}", self.url, function.as_ref());
102 Builder::new(url, self.schema.clone(), self.headers.clone()).rpc(params)
103 }
104}