elasticctl_api/
content_codec.rs1use elasticctl_core::{Error, ErrorKind, Result};
2use serde::{Serialize, de::DeserializeOwned};
3use serde_json::Value;
4use std::path::Path;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ContentFormat {
8 Json,
9 Yaml,
10}
11
12impl ContentFormat {
13 pub fn from_path(path: &Path) -> Self {
14 match path.extension().and_then(|extension| extension.to_str()) {
15 Some("yaml") | Some("yml") => Self::Yaml,
16 _ => Self::Json,
17 }
18 }
19}
20
21pub fn encode_sequence<T: Serialize>(values: &[T], format: ContentFormat) -> Result<String> {
22 match format {
23 ContentFormat::Json => serde_json::to_string_pretty(values)
24 .map_err(|error| Error::new(ErrorKind::Error, format!("encoding JSON: {error}"))),
25 ContentFormat::Yaml => serde_yaml_ng::to_string(values)
26 .map_err(|error| Error::new(ErrorKind::Error, format!("encoding YAML: {error}"))),
27 }
28}
29
30pub fn decode_sequence<T: DeserializeOwned>(
31 body: &str,
32 format: ContentFormat,
33 item_name: &str,
34) -> Result<Vec<T>> {
35 let values: Vec<Value> = match format {
36 ContentFormat::Json => serde_json::from_str(body).map_err(|error| {
37 Error::new(
38 ErrorKind::Error,
39 format!("parsing JSON {item_name} sequence: {error}"),
40 )
41 })?,
42 ContentFormat::Yaml => serde_yaml_ng::from_str(body).map_err(|error| {
43 Error::new(
44 ErrorKind::Error,
45 format!("parsing YAML {item_name} sequence: {error}"),
46 )
47 })?,
48 };
49
50 values
51 .into_iter()
52 .enumerate()
53 .map(|(index, value)| {
54 serde_json::from_value(value).map_err(|error| {
55 Error::new(
56 ErrorKind::Error,
57 format!("{item_name} at index {index}: {error}"),
58 )
59 })
60 })
61 .collect()
62}