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

getInternallyTaggedCodec: preserve tag when decoding #26

Merged
merged 6 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 1 addition & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -682,8 +682,7 @@ const getInternallyTaggedMemberCodec =
(i, ctx) =>
pipe(
t.type({ [tagKey]: t.literal(tag) }).validate(i, ctx),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
E.chain(({ [tagKey]: _, ...rest }) => vc.validate(rest, ctx)),
E.chain(x => vc.validate(x, ctx)),
E.map(x =>
Sum.deserialize(sum)([tag, x] as unknown as Sum.Serialized<A>),
),
Expand Down
17 changes: 11 additions & 6 deletions test/unit/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,20 +540,22 @@ describe("index", () => {
})

describe("getInternallyTaggedCodec", () => {
type T = Sum.Member<"A"> | Sum.Member<"B", { readonly foo: number }>
type T =
| Sum.Member<"A">
| Sum.Member<"B", { readonly tag: "B"; readonly foo: number }>
OliverJAsh marked this conversation as resolved.
Show resolved Hide resolved
const T = Sum.create<T>()
const {
mk: { A, B },
} = T

const c = getInternallyTaggedCodec("tag")(T)({
A: nullaryFromEmpty,
B: t.strict({ foo: NumberFromString }),
B: t.strict({ tag: t.literal("B"), foo: NumberFromString }),
})

it("type guards", () => {
expect(c.is(A)).toBe(true)
expect(c.is(B({ foo: 123 }))).toBe(true)
expect(c.is(B({ tag: "B", foo: 123 }))).toBe(true)

expect(c.is("A")).toBe(false)
expect(c.is("B")).toBe(false)
Expand All @@ -566,7 +568,10 @@ describe("index", () => {

it("encodes", () => {
expect(c.encode(A)).toEqual({ tag: "A" })
expect(c.encode(B({ foo: 123 }))).toEqual({ tag: "B", foo: "123" })
expect(c.encode(B({ tag: "B", foo: 123 }))).toEqual({
tag: "B",
foo: "123",
})
})

it("does not decode bad inputs", () => {
Expand All @@ -576,7 +581,7 @@ describe("index", () => {
expect(f("A")).toBe(true)
expect(f("B")).toBe(true)
expect(f(A)).toBe(true)
expect(f(B({ foo: 123 }))).toBe(true)
expect(f(B({ tag: "B", foo: 123 }))).toBe(true)
expect(f({})).toBe(true)
expect(f(false)).toBe(true)
expect(f("123")).toBe(true)
Expand All @@ -589,7 +594,7 @@ describe("index", () => {
fc.assert(
fc.property(fc.integer({ min: 0 }), n =>
expect(c.decode({ tag: "B", foo: String(n) })).toEqual(
E.right(B({ foo: n })),
E.right(B({ tag: "B", foo: n })),
),
),
)
Expand Down
Loading