1use crate::{http, parse_response, utils, Client, Error};
2
3const FULL_ACCESS: &str = "full_access";
4const SENDING_ACCESS: &str = "sending_access";
5
6#[derive(serde_derive::Serialize)]
7pub struct CreateRequest {
8 pub name: String,
9 pub permission: Permission,
10 pub domain_id: String,
11}
12
13#[derive(serde_derive::Serialize)]
14pub enum Permission {
15 #[serde(rename(serialize = "full_access"))]
16 FullAccess,
17 #[serde(rename(serialize = "sending_access"))]
18 SendingAccess,
19}
20
21impl std::fmt::Display for Permission {
22 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
23 match self {
24 Self::FullAccess => {
25 write!(f, "{}", FULL_ACCESS)
26 }
27 Self::SendingAccess => {
28 write!(f, "{}", SENDING_ACCESS)
29 }
30 }
31 }
32}
33
34#[derive(serde_derive::Deserialize)]
35pub struct CreateResponse {
36 pub id: String,
37 pub token: String,
38}
39
40#[derive(serde_derive::Deserialize)]
41pub struct APIKey {
42 pub id: String,
43 pub name: String,
44 pub created_at: String,
45}
46
47pub async fn create(client: &Client, r: CreateRequest) -> Result<CreateResponse, Error> {
48 let request_json = serde_json::to_string(&r).map_err(Error::JSON)?;
49
50 let url = utils::url::api_keys::base(&client.base_url);
51 let request = http::Request::new(http::Method::Post, &url, Some(request_json.to_string()));
52
53 let response = parse_response(client.perform(request).await.map_err(Error::Client)?).await?;
54 serde_json::from_str(&response).map_err(Error::JSON)
55}
56
57#[derive(serde_derive::Deserialize)]
58pub struct ListResponse {
59 pub data: Vec<APIKey>,
60}
61
62pub async fn list(client: &Client) -> Result<ListResponse, Error> {
63 let url = utils::url::api_keys::base(&client.base_url);
64 let request = http::Request::new(http::Method::Get, &url, None);
65
66 let response = parse_response(client.perform(request).await.map_err(Error::Client)?).await?;
67 serde_json::from_str(&response).map_err(Error::JSON)
68}
69
70pub async fn delete(client: &Client, api_key_id: &str) -> Result<(), Error> {
71 let url = utils::url::api_keys::with_id(&client.base_url, api_key_id);
72 let request = http::Request::new(http::Method::Delete, &url, None);
73
74 parse_response(client.perform(request).await.map_err(Error::Client)?).await?;
75 Ok(())
76}
77
78#[cfg(test)]
79mod test {
80 use super::*;
81
82 #[test]
83 fn test_serialize_create_request() {
84 let expected = "{\"permission\":\"full_access\",\"domain_id\":\"test-domain-id\"}";
85 let json = serde_json::to_string(&CreateRequest {
86 name: "test-api-key".to_owned(),
87 permission: Permission::FullAccess,
88 domain_id: "test-domain-id".to_owned(),
89 })
90 .unwrap();
91
92 assert_eq!(expected, json);
93 }
94}