forevervm_sdk/api/
token.rs1use serde::{Deserialize, Serialize};
2use std::{fmt::Display, str::FromStr};
3
4const SEPARATOR: &str = ".";
5
6#[derive(Debug, Clone)]
7pub struct ApiToken {
8 pub id: String,
9 pub token: String,
10}
11
12impl ApiToken {
13 pub fn new(token: String) -> Result<Self, ApiTokenError> {
14 let (id, token) = token
15 .split_once(SEPARATOR)
16 .ok_or(ApiTokenError::InvalidFormat)?;
17 Ok(Self {
18 id: id.to_string(),
19 token: token.to_string(),
20 })
21 }
22}
23
24impl Serialize for ApiToken {
25 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
26 where
27 S: serde::Serializer,
28 {
29 serializer.serialize_str(&self.to_string())
30 }
31}
32
33impl<'de> Deserialize<'de> for ApiToken {
34 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
35 where
36 D: serde::Deserializer<'de>,
37 {
38 let s = String::deserialize(deserializer)?;
39 Self::from_str(&s).map_err(serde::de::Error::custom)
40 }
41}
42
43#[derive(thiserror::Error, Debug)]
44pub enum ApiTokenError {
45 #[error("Invalid token format")]
46 InvalidFormat,
47}
48
49impl FromStr for ApiToken {
50 type Err = ApiTokenError;
51
52 fn from_str(s: &str) -> Result<Self, Self::Err> {
53 let (id, token) = s
54 .split_once(SEPARATOR)
55 .ok_or(ApiTokenError::InvalidFormat)?;
56 Ok(Self {
57 id: id.to_string(),
58 token: token.to_string(),
59 })
60 }
61}
62
63impl Display for ApiToken {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 write!(f, "{}{}{}", self.id, SEPARATOR, self.token)
66 }
67}