Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add epoch_millis_to_iso8601 transform function #188

Merged
merged 2 commits into from
Aug 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading