Skip to content

Commit

Permalink
Add epoch_millis_to_iso8601 transform function
Browse files Browse the repository at this point in the history
  • Loading branch information
kpapadatos authored and rtyler committed Aug 16, 2024
1 parent 8114666 commit 4d2fcbd
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/transforms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ lazy_static! {
"epoch_seconds_to_iso8601",
Box::new(create_epoch_seconds_to_iso8601_fn()),
);
runtime.register_function(
"epoch_millis_to_iso8601",
Box::new(create_epoch_millis_to_iso8601_fn()),
);
runtime.register_function(
"epoch_micros_to_iso8601",
Box::new(create_epoch_micros_to_iso8601_fn()),
Expand Down Expand Up @@ -184,6 +188,13 @@ fn create_epoch_seconds_to_iso8601_fn() -> CustomFunction {
}

// TODO: Consolidate these custom function factories
fn create_epoch_millis_to_iso8601_fn() -> CustomFunction {
CustomFunction::new(
Signature::new(vec![ArgumentType::Number], None),
Box::new(jmespath_epoch_millis_to_iso8601),
)
}

fn create_epoch_micros_to_iso8601_fn() -> CustomFunction {
CustomFunction::new(
Signature::new(vec![ArgumentType::Number], None),
Expand Down Expand Up @@ -214,12 +225,14 @@ fn substr(args: &[Rcvar], context: &mut Context) -> Result<Rcvar, JmespathError>

enum EpochUnit {
Seconds(i64),
Milliseconds(i64),
Microseconds(i64),
}

fn iso8601_from_epoch(epoch_unit: EpochUnit) -> String {
let dt = match epoch_unit {
EpochUnit::Seconds(s) => Utc.timestamp_nanos(s * 1_000_000_000),
EpochUnit::Milliseconds(ms) => Utc.timestamp_nanos(ms * 1_000_000),
EpochUnit::Microseconds(u) => Utc.timestamp_nanos(u * 1000),
};

Expand All @@ -236,6 +249,16 @@ fn jmespath_epoch_seconds_to_iso8601(
Ok(Arc::new(variable))
}

fn jmespath_epoch_millis_to_iso8601(
args: &[Rcvar],
context: &mut Context,
) -> Result<Rcvar, JmespathError> {
let millis = i64_from_args(args, context, 0)?;
let value = serde_json::Value::String(iso8601_from_epoch(EpochUnit::Milliseconds(millis)));
let variable = Variable::try_from(value)?;
Ok(Arc::new(variable))
}

fn jmespath_epoch_micros_to_iso8601(
args: &[Rcvar],
context: &mut Context,
Expand Down

0 comments on commit 4d2fcbd

Please sign in to comment.