use super::{ApiLinks, ApiMeta};
use super::{HasPagination, HasResponse, HasValue};
use crate::method::{Create, Delete, Get, List, Update};
use crate::request::Request;
use crate::request::SshKeyRequest;
use crate::{ROOT_URL, STATIC_URL_ERROR};
use getset::{Getters, Setters};
use serde::Serialize;
use std::fmt::Display;
use url::Url;
const ACCOUNT_SEGMENT: &str = "account";
const KEYS_SEGMENT: &str = "keys";
#[derive(Deserialize, Serialize, Debug, Clone, Getters, Setters)]
#[get = "pub"]
pub struct SshKey {
id: usize,
fingerprint: String,
public_key: String,
name: String,
}
impl SshKey {
pub fn create<N>(name: N, public_key: N) -> SshKeyRequest<Create, SshKey>
where N: AsRef<str> + Serialize + Display, {
let mut url = ROOT_URL.clone();
url.path_segments_mut()
.expect(STATIC_URL_ERROR)
.push(ACCOUNT_SEGMENT)
.push(KEYS_SEGMENT);
let mut req = Request::new(url);
req.set_body(json!({
"name": name,
"public_key": public_key,
}));
req
}
pub fn list() -> SshKeyRequest<List, Vec<SshKey>> {
let mut url = ROOT_URL.clone();
url.path_segments_mut()
.expect(STATIC_URL_ERROR)
.push(ACCOUNT_SEGMENT)
.push(KEYS_SEGMENT);
Request::new(url)
}
pub fn get<S: Serialize + Display>(id: S) -> SshKeyRequest<Get, SshKey> {
let mut url = ROOT_URL.clone();
url.path_segments_mut()
.expect(STATIC_URL_ERROR)
.push(ACCOUNT_SEGMENT)
.push(KEYS_SEGMENT)
.push(&format!("{}", id));
Request::new(url)
}
pub fn update<S: Serialize + Display>(id: S) -> SshKeyRequest<Update, SshKey> {
let mut url = ROOT_URL.clone();
url.path_segments_mut()
.expect(STATIC_URL_ERROR)
.push(ACCOUNT_SEGMENT)
.push(KEYS_SEGMENT)
.push(&format!("{}", id));
Request::new(url)
}
pub fn delete<S: Serialize + Display>(id: S) -> SshKeyRequest<Delete, ()> {
let mut url = ROOT_URL.clone();
url.path_segments_mut()
.expect(STATIC_URL_ERROR)
.push(ACCOUNT_SEGMENT)
.push(KEYS_SEGMENT)
.push(&format!("{}", id));
Request::new(url)
}
}
impl SshKeyRequest<Update, SshKey> {
pub fn name<S: AsRef<str> + Display + Serialize>(mut self, val: S) -> Self {
self.body_mut()["name"] = json!(val);
self
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct SshKeyListResponse {
ssh_keys: Vec<SshKey>,
links: ApiLinks,
meta: ApiMeta
}
impl HasResponse for Vec<SshKey> {
type Response = SshKeyListResponse;
}
impl HasPagination for SshKeyListResponse {
fn next_page(&self) -> Option<Url> {
self.links.next()
}
}
impl HasValue for SshKeyListResponse {
type Value = Vec<SshKey>;
fn value(self) -> Vec<SshKey> {
self.ssh_keys
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct SshKeyResponse {
ssh_key: SshKey
}
impl HasResponse for SshKey {
type Response = SshKeyResponse;
}
impl HasValue for SshKeyResponse {
type Value = SshKey;
fn value(self) -> SshKey {
self.ssh_key
}
}