use std::collections::BTreeMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::command::CommandPath;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct OutputEnvelopeMetaV1 {
pub version: String,
pub command: CommandPath,
pub timestamp: String,
}
impl OutputEnvelopeMetaV1 {
pub fn new(version: &str, command: CommandPath, timestamp: &str) -> Result<Self, String> {
if version.trim().is_empty() {
return Err("meta.version cannot be empty".to_string());
}
if timestamp.trim().is_empty() {
return Err("meta.timestamp cannot be empty".to_string());
}
Ok(Self { version: version.to_string(), command, timestamp: timestamp.to_string() })
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct OutputEnvelopeV1 {
pub status: String,
pub data: Value,
pub meta: OutputEnvelopeMetaV1,
}
impl OutputEnvelopeV1 {
#[must_use]
pub fn success(data: Value, meta: OutputEnvelopeMetaV1) -> Self {
Self { status: "ok".to_string(), data, meta }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
pub struct ErrorDetailsV1 {
pub failure: Option<String>,
#[serde(default)]
pub context: BTreeMap<String, Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ErrorPayloadV1 {
pub code: String,
pub message: String,
pub category: String,
#[serde(default)]
pub details: Option<ErrorDetailsV1>,
}
impl ErrorPayloadV1 {
pub fn new(code: &str, message: &str, category: &str) -> Result<Self, String> {
if code.trim().is_empty() {
return Err("error.code cannot be empty".to_string());
}
if message.trim().is_empty() {
return Err("error.message cannot be empty".to_string());
}
if category.trim().is_empty() {
return Err("error.category cannot be empty".to_string());
}
Ok(Self {
code: code.to_string(),
message: message.to_string(),
category: category.to_string(),
details: None,
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ErrorEnvelopeV1 {
pub status: String,
pub error: ErrorPayloadV1,
pub meta: OutputEnvelopeMetaV1,
}
impl ErrorEnvelopeV1 {
#[must_use]
pub fn failure(error: ErrorPayloadV1, meta: OutputEnvelopeMetaV1) -> Self {
Self { status: "error".to_string(), error, meta }
}
}