Skip to content

Commit

Permalink
add DateTimeUtcFromDate schema (#3956)
Browse files Browse the repository at this point in the history
Co-authored-by: Giulio Canti <giulio.canti@gmail.com>
  • Loading branch information
2 people authored and tim-smart committed Dec 22, 2024
1 parent 7e5cf15 commit 2d79805
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/gold-squids-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

add DateTimeUtcFromDate schema
16 changes: 16 additions & 0 deletions packages/effect/src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6496,6 +6496,22 @@ export class DateTimeUtcFromNumber extends transformOrFail(
}
).annotations({ identifier: "DateTimeUtcFromNumber" }) {}

/**
* Defines a schema that attempts to convert a `Date` to a `DateTime.Utc` instance using the `DateTime.unsafeMake` constructor.
*
* @category DateTime.Utc transformations
* @since 3.12.0
*/
export class DateTimeUtcFromDate extends transformOrFail(
DateFromSelf.annotations({ description: "a Date that will be parsed into a DateTime.Utc" }),
DateTimeUtcFromSelf,
{
strict: true,
decode: decodeDateTime,
encode: (dt) => ParseResult.succeed(dateTime.toDateUtc(dt))
}
).annotations({ identifier: "DateTimeUtcFromDate" }) {}

/**
* Defines a schema that attempts to convert a `string` to a `DateTime.Utc` instance using the `DateTime.unsafeMake` constructor.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as DateTime from "effect/DateTime"
import * as S from "effect/Schema"
import * as Util from "effect/test/Schema/TestUtils"
import { describe, expect, it } from "vitest"

describe("DateTimeUtcFromDate", () => {
it("decoding", async () => {
await Util.expectDecodeUnknownSuccess(S.DateTimeUtcFromDate, new Date(0), DateTime.unsafeMake(0))
await Util.expectDecodeUnknownSuccess(
S.DateTimeUtcFromDate,
new Date("2024-12-06T00:00:00Z"),
DateTime.unsafeMake({ day: 6, month: 12, year: 2024, hour: 0, minute: 0, second: 0, millisecond: 0 })
)

await Util.expectDecodeUnknownFailure(
S.DateTimeUtcFromDate,
null,
`DateTimeUtcFromDate
└─ Encoded side transformation failure
└─ Expected DateFromSelf, actual null`
)
await Util.expectDecodeUnknownFailure(
S.DateTimeUtcFromDate,
new Date(NaN),
`DateTimeUtcFromDate
└─ Transformation process failure
└─ Expected DateTimeUtcFromDate, actual Invalid Date`
)
})

it("encoding", async () => {
await Util.expectEncodeSuccess(S.DateTimeUtcFromDate, DateTime.unsafeMake(0), new Date(0))
expect(
S.encodeSync(S.DateTimeUtcFromDate)(
DateTime.unsafeMake({ day: 6, month: 12, year: 2024, hour: 0, minute: 0, second: 0, millisecond: 0 })
)
).toStrictEqual(new Date("2024-12-06T00:00:00Z"))
})
})

0 comments on commit 2d79805

Please sign in to comment.