use monostate::MustBe;
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "Assertion")]
pub struct Obj {
#[serde(rename = "@context")]
#[builder(default = MustBe!("https://w3id.org/openbadges/v2"))]
pub context: MustBe!("https://w3id.org/openbadges/v2"),
#[builder(default = MustBe!("CryptographicKey"))]
pub r#type: MustBe!("CryptographicKey"),
#[builder(setter(into))]
pub id: String,
#[builder(setter(into))]
pub owner: String,
#[builder(setter(into))]
pub public_key_pem: String,
}
impl Obj {
pub fn new<S: Into<String>>(id: S, owner: S, public_key_pem: S) -> Self {
Self {
context: MustBe!("https://w3id.org/openbadges/v2"),
r#type: MustBe!("CryptographicKey"),
id: id.into(),
owner: owner.into(),
public_key_pem: public_key_pem.into(),
}
}
}
impl super::ToJsonLd for Obj {}
#[cfg(test)]
mod tests {
use super::*;
use crate::objects::ToJsonLd;
const EXP_JSON_LD_SIMPLE: &str = r#"{
"@context": "https://w3id.org/openbadges/v2",
"type": "CryptographicKey",
"id": "https://example.org/publicKey.json",
"owner": "https://example.org/organization.json",
"publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBG0BA...OClDQAB\n-----END PUBLIC KEY-----\n"
}"#;
#[test]
fn test_new_simple() -> Result<(), Box<dyn std::error::Error>> {
let obj = Obj::new(
"https://example.org/publicKey.json",
"https://example.org/organization.json",
"-----BEGIN PUBLIC KEY-----\nMIIBG0BA...OClDQAB\n-----END PUBLIC KEY-----\n",
);
let json_ld = obj.to_json_ld()?;
assert_eq!(&json_ld, EXP_JSON_LD_SIMPLE);
Ok(())
}
#[test]
fn test_builder_simple() -> Result<(), Box<dyn std::error::Error>> {
let obj = Obj::builder()
.id("https://example.org/publicKey.json")
.owner("https://example.org/organization.json")
.public_key_pem(
"-----BEGIN PUBLIC KEY-----\nMIIBG0BA...OClDQAB\n-----END PUBLIC KEY-----\n",
)
.build();
let json_ld = obj.to_json_ld()?;
assert_eq!(&json_ld, EXP_JSON_LD_SIMPLE);
Ok(())
}
#[test]
fn test_rawe_key() -> Result<(), Box<dyn std::error::Error>> {
let obj = Obj::new(
"https://example.org/publicKey.json",
"https://example.org/organization.json",
"-----BEGIN PUBLIC KEY-----
MIIBG0BA...OClDQAB
-----END PUBLIC KEY-----
",
);
let json_ld = obj.to_json_ld()?;
assert_eq!(&json_ld, EXP_JSON_LD_SIMPLE);
Ok(())
}
}