summaryrefslogtreecommitdiffstats
path: root/cli/src/api/connection.rs
blob: 5505afb0164f017c70abc53ac407aa3464f6e643 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 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()?)
    }

    pub fn patch(&self, resource: &str, data: &str) -> Result<String, Box<dyn Error>> {
        Ok(ureq::patch(&format!("{}/{}", &self.url, resource))
            .set("Authorization", &format!("Bearer {}", self.jwt_token))
            .set("Content-Type", "application/json")
            .send_string(&data)?
            .into_string()?)
    }
}