diff --git a/crates/backend/src/typegen.rs b/crates/backend/src/typegen.rs index 8a3a1383..94e6c899 100644 --- a/crates/backend/src/typegen.rs +++ b/crates/backend/src/typegen.rs @@ -168,6 +168,7 @@ static KNOWN_TYPES: Lazy> = Lazy::new(|| { ("BigInt64Array", "BigInt64Array"), ("BigUint64Array", "BigUint64Array"), ("DataView", "DataView"), + ("DateTime", "Date"), ("Date", "Date"), ("JsDate", "Date"), ("JsBuffer", "Buffer"), diff --git a/crates/napi/Cargo.toml b/crates/napi/Cargo.toml index 1c9f344b..1fe332a1 100644 --- a/crates/napi/Cargo.toml +++ b/crates/napi/Cargo.toml @@ -18,9 +18,10 @@ independent = true [features] async = ["tokio_rt"] compat-mode = [] -default = ["napi3", "compat-mode"] # for most Node.js users +default = ["napi3", "compat-mode"] # for most Node.js users experimental = ["napi-sys/experimental"] -full = ["latin1", "napi8", "async", "serde-json", "experimental"] +chrono_date = ["chrono"] +full = ["latin1", "napi8", "async", "serde-json", "experimental", "chrono_date"] latin1 = ["encoding_rs"] napi1 = [] napi2 = ["napi1"] @@ -48,12 +49,16 @@ tokio_time = ["tokio/time"] [dependencies] ctor = "0.1" lazy_static = "1" -napi-sys = {version = "2.1.0", path = "../sys"} +napi-sys = { version = "2.1.0", path = "../sys" } [dependencies.encoding_rs] optional = true version = "0.8" +[dependencies.chrono] +optional = true +version = "0.4" + [dependencies.tokio] features = ["rt", "rt-multi-thread", "sync"] optional = true @@ -68,4 +73,8 @@ optional = true version = "1" [target.'cfg(windows)'.dependencies] -windows = {version = "0.30", features = ["Win32_System_WindowsProgramming", "Win32_System_LibraryLoader", "Win32_Foundation"]} +windows = { version = "0.30", features = [ + "Win32_System_WindowsProgramming", + "Win32_System_LibraryLoader", + "Win32_Foundation", +] } diff --git a/crates/napi/src/bindgen_runtime/js_values.rs b/crates/napi/src/bindgen_runtime/js_values.rs index 2469f1c8..a835621b 100644 --- a/crates/napi/src/bindgen_runtime/js_values.rs +++ b/crates/napi/src/bindgen_runtime/js_values.rs @@ -8,6 +8,8 @@ mod arraybuffer; mod bigint; mod boolean; mod buffer; +#[cfg(all(feature = "chrono_date", feature = "napi5"))] +mod date; mod either; mod external; mod function; diff --git a/crates/napi/src/bindgen_runtime/js_values/date.rs b/crates/napi/src/bindgen_runtime/js_values/date.rs new file mode 100644 index 00000000..8188fcb6 --- /dev/null +++ b/crates/napi/src/bindgen_runtime/js_values/date.rs @@ -0,0 +1,52 @@ +use crate::{bindgen_prelude::*, check_status, sys, ValueType}; +use chrono::{DateTime, NaiveDateTime, Utc}; + +impl TypeName for DateTime { + fn type_name() -> &'static str { + "DateTime" + } + + fn value_type() -> ValueType { + ValueType::Object + } +} + +impl ValidateNapiValue for DateTime { + fn type_of() -> Vec { + vec![ValueType::Object] + } +} + +impl ToNapiValue for DateTime { + unsafe fn to_napi_value(env: sys::napi_env, val: DateTime) -> Result { + let mut ptr = std::ptr::null_mut(); + let millis_since_epoch_utc = val.timestamp_millis() as f64; + + check_status!( + unsafe { sys::napi_create_date(env, millis_since_epoch_utc, &mut ptr) }, + "Failed to convert rust type `DateTime` into napi value", + )?; + + Ok(ptr) + } +} + +impl FromNapiValue for DateTime { + unsafe fn from_napi_value(env: sys::napi_env, napi_val: sys::napi_value) -> Result { + let mut milliseconds_since_epoch_utc = 0.0; + + check_status!( + unsafe { sys::napi_get_date_value(env, napi_val, &mut milliseconds_since_epoch_utc) }, + "Failed to convert napi value into rust type `DateTime`", + )?; + + let milliseconds_since_epoch_utc = milliseconds_since_epoch_utc as i64; + let timestamp_seconds = milliseconds_since_epoch_utc / 1_000; + let naive = NaiveDateTime::from_timestamp_opt( + timestamp_seconds, + (milliseconds_since_epoch_utc % 1_000 * 1_000_000) as u32, + ) + .ok_or_else(|| Error::new(Status::DateExpected, "Found invalid date".to_owned()))?; + Ok(DateTime::::from_utc(naive, Utc)) + } +} diff --git a/examples/napi/Cargo.toml b/examples/napi/Cargo.toml index 9ccaf160..242958e8 100644 --- a/examples/napi/Cargo.toml +++ b/examples/napi/Cargo.toml @@ -9,12 +9,22 @@ version = "0.1.0" crate-type = ["cdylib"] [dependencies] +chrono = "0.4" futures = "0.3" -napi = {path = "../../crates/napi", default-features = false, features = ["tokio_fs", "napi8", "tokio_rt", "serde-json", "async", "experimental", "latin1"]} -napi-derive = {path = "../../crates/macro", features = ["type-def"]} +napi = { path = "../../crates/napi", default-features = false, features = [ + "tokio_fs", + "napi8", + "tokio_rt", + "serde-json", + "async", + "experimental", + "latin1", + "chrono_date", +] } +napi-derive = { path = "../../crates/macro", features = ["type-def"] } serde = "1" serde_derive = "1" serde_json = "1" [build-dependencies] -napi-build = {path = "../../crates/build"} +napi-build = { path = "../../crates/build" } diff --git a/examples/napi/__test__/typegen.spec.ts.md b/examples/napi/__test__/typegen.spec.ts.md index 58ce38af..6f3cce0f 100644 --- a/examples/napi/__test__/typegen.spec.ts.md +++ b/examples/napi/__test__/typegen.spec.ts.md @@ -41,6 +41,8 @@ Generated by [AVA](https://avajs.dev). export function readFile(callback: (arg0: Error | undefined, arg1?: string | undefined | null) => void): void␊ export function returnJsFunction(): (...args: any[]) => any␊ export function dateToNumber(input: Date): number␊ + export function chronoDateToMillis(input: Date): number␊ + export function chronoDateAdd1Minute(input: Date): Date␊ export function eitherStringOrNumber(input: string | number): number␊ export function returnEither(input: number): string | number␊ export function either3(input: string | number | boolean): number␊ diff --git a/examples/napi/__test__/typegen.spec.ts.snap b/examples/napi/__test__/typegen.spec.ts.snap index c8cab00c..d07cb6c3 100644 Binary files a/examples/napi/__test__/typegen.spec.ts.snap and b/examples/napi/__test__/typegen.spec.ts.snap differ diff --git a/examples/napi/__test__/values.spec.ts b/examples/napi/__test__/values.spec.ts index a5c30f41..d6ba3956 100644 --- a/examples/napi/__test__/values.spec.ts +++ b/examples/napi/__test__/values.spec.ts @@ -83,7 +83,9 @@ import { testSerdeRoundtrip, createObjWithProperty, dateToNumber, + chronoDateToMillis, derefUint8Array, + chronoDateAdd1Minute, } from '../' test('export const', (t) => { @@ -564,3 +566,12 @@ Napi5Test('Date test', (t) => { const fixture = new Date('2016-12-24') t.is(dateToNumber(fixture), fixture.valueOf()) }) + +Napi5Test('Date to chrono test', (t) => { + const fixture = new Date('2022-02-09T19:31:55.396Z') + t.is(chronoDateToMillis(fixture), fixture.getTime()) + t.deepEqual( + chronoDateAdd1Minute(fixture), + new Date(fixture.getTime() + 60 * 1000), + ) +}) diff --git a/examples/napi/index.d.ts b/examples/napi/index.d.ts index ef8eb4e3..9f9da35d 100644 --- a/examples/napi/index.d.ts +++ b/examples/napi/index.d.ts @@ -31,6 +31,8 @@ export function optionOnly(callback: (arg0?: string | undefined | null) => void) export function readFile(callback: (arg0: Error | undefined, arg1?: string | undefined | null) => void): void export function returnJsFunction(): (...args: any[]) => any export function dateToNumber(input: Date): number +export function chronoDateToMillis(input: Date): number +export function chronoDateAdd1Minute(input: Date): Date export function eitherStringOrNumber(input: string | number): number export function returnEither(input: number): string | number export function either3(input: string | number | boolean): number diff --git a/examples/napi/src/date.rs b/examples/napi/src/date.rs index 6987cd53..d1d00ca5 100644 --- a/examples/napi/src/date.rs +++ b/examples/napi/src/date.rs @@ -1,6 +1,17 @@ +use chrono::{Duration, Utc}; use napi::bindgen_prelude::*; #[napi] fn date_to_number(input: Date) -> Result { input.value_of() } + +#[napi] +fn chrono_date_to_millis(input: chrono::DateTime) -> i64 { + input.timestamp_millis() +} + +#[napi] +fn chrono_date_add_1_minute(input: chrono::DateTime) -> chrono::DateTime { + input + Duration::minutes(1) +}