summaryrefslogtreecommitdiffstats
path: root/cli/src/api/connection.rs
diff options
context:
space:
mode:
authorHarald Eilertsen <haraldei@anduin.net>2024-04-24 11:27:42 +0200
committerHarald Eilertsen <haraldei@anduin.net>2024-04-24 11:27:42 +0200
commita4dbf815cc418514a268ca54464c2d1b9c413055 (patch)
tree81d6a5944a00839f37c7d9ea469274f8d8425338 /cli/src/api/connection.rs
parent1c3e4dba9fe90faa318933a99eecdb9cd5e7481a (diff)
downloadfaktura-a4dbf815cc418514a268ca54464c2d1b9c413055.tar.gz
faktura-a4dbf815cc418514a268ca54464c2d1b9c413055.tar.bz2
faktura-a4dbf815cc418514a268ca54464c2d1b9c413055.zip
cli: Add feature to save clients to the db.
Also introduces a Connection object to handle the actual connection to the remote API. We also load the remote API url and jwt token from the process environment so these are no longer hardcoded into the source code.
Diffstat (limited to 'cli/src/api/connection.rs')
-rw-r--r--cli/src/api/connection.rs36
1 files changed, 36 insertions, 0 deletions
diff --git a/cli/src/api/connection.rs b/cli/src/api/connection.rs
new file mode 100644
index 0000000..f1d7f1c
--- /dev/null
+++ b/cli/src/api/connection.rs
@@ -0,0 +1,36 @@
+// SPDX-FileCopyrightText: 2024 Eilertsens Kodeknekkeri
+// SPDX-FileCopyrightText: 2024 Harald Eilertsen
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use serde::{Deserialize, Serialize};
+use std::error::Error;
+
+pub struct Connection {
+ pub url: String,
+ pub jwt_token: String,
+}
+
+impl Connection {
+ pub fn new<T: Into<String>>(url: T, jwt_token: T) -> Connection {
+ Connection {
+ url: url.into(),
+ jwt_token: jwt_token.into(),
+ }
+ }
+
+ pub fn get<T: for <'de> Deserialize<'de>>(&self, resource: &str) -> Result<T, Box<dyn Error>> {
+ Ok(ureq::get(&format!("{}/{}", self.url, resource))
+ .set("Accept", "application/json")
+ .call()?
+ .into_json()?)
+ }
+
+ pub fn post<T: Serialize>(&self, resource: &str, data: &T) -> Result<String, Box<dyn Error>> {
+ Ok(ureq::post(&format!("{}/{}", self.url, resource))
+ .set("Authorization", &format!("Bearer {}", self.jwt_token))
+ .set("Content-Type", "application/json")
+ .send_json(&data)?
+ .into_string()?)
+ }
+}