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

Handle record keys outside domain #705

Merged
merged 3 commits into from
Dec 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ node_modules
dev
coverage
declaration/out/src
.DS_Store
67 changes: 29 additions & 38 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,42 +330,17 @@ function enumerableRecord<D extends Mixed, C extends Mixed>(
name = `{ [K in ${domain.name}]: ${codomain.name} }`
): RecordC<D, C> {
const len = keys.length
const props: Props = {}
for (let i = 0; i < len; i++) {
props[keys[i]] = codomain
}
const exactCodec = strict(props, name)

return new DictionaryType(
name,
(u): u is { [K in TypeOf<D>]: TypeOf<C> } => UnknownRecord.is(u) && keys.every((k) => codomain.is(u[k])),
(u, c) => {
const e = UnknownRecord.validate(u, c)
if (isLeft(e)) {
return e
}
const o = e.right
const a: { [key: string]: any } = {}
const errors: Errors = []
let changed = false
for (let i = 0; i < len; i++) {
const k = keys[i]
const ok = o[k]
const codomainResult = codomain.validate(ok, appendContext(c, k, codomain, ok))
if (isLeft(codomainResult)) {
pushAll(errors, codomainResult.left)
} else {
const vok = codomainResult.right
changed = changed || vok !== ok
a[k] = vok
}
}
return errors.length > 0 ? failures(errors) : success((changed || Object.keys(o).length !== len ? a : o) as any)
},
codomain.encode === identity
? identity
: (a: any) => {
const s: { [key: string]: any } = {}
for (let i = 0; i < len; i++) {
const k = keys[i]
s[k] = codomain.encode(a[k])
}
return s as any
},
(u): u is { [K in TypeOf<D>]: TypeOf<C> } => exactCodec.is(u),
exactCodec.validate,
exactCodec.encode,
domain,
codomain
)
Expand All @@ -389,6 +364,22 @@ export function getDomainKeys<D extends Mixed>(domain: D): Record<string, unknow
return undefined
}

function stripNonDomainKeys(o: any, domain: Mixed) {
const keys = Object.keys(o)
const len = keys.length
let shouldStrip = false
const r: any = {}
for (let i = 0; i < len; i++) {
const k = keys[i]
if (domain.is(k)) {
r[k] = o[k]
} else {
shouldStrip = true
}
}
return shouldStrip ? r : o
}

function nonEnumerableRecord<D extends Mixed, C extends Mixed>(
domain: D,
codomain: C,
Expand All @@ -398,7 +389,7 @@ function nonEnumerableRecord<D extends Mixed, C extends Mixed>(
name,
(u): u is { [K in TypeOf<D>]: TypeOf<C> } => {
if (UnknownRecord.is(u)) {
return Object.keys(u).every((k) => domain.is(k) && codomain.is(u[k]))
return Object.keys(u).every((k) => !domain.is(k) || codomain.is(u[k]))
}
return isAnyC(codomain) && Array.isArray(u)
},
Expand All @@ -414,7 +405,7 @@ function nonEnumerableRecord<D extends Mixed, C extends Mixed>(
const ok = u[k]
const domainResult = domain.validate(k, appendContext(c, k, domain, k))
if (isLeft(domainResult)) {
pushAll(errors, domainResult.left)
changed = true
} else {
const vk = domainResult.right
changed = changed || vk !== k
Expand All @@ -437,10 +428,10 @@ function nonEnumerableRecord<D extends Mixed, C extends Mixed>(
return failure(u, c)
},
domain.encode === identity && codomain.encode === identity
? identity
? (a) => stripNonDomainKeys(a, domain)
: (a) => {
const s: { [key: string]: any } = {}
const keys = Object.keys(a)
const keys = Object.keys(stripNonDomainKeys(a, domain))
const len = keys.length
for (let i = 0; i < len; i++) {
const k = keys[i]
Expand Down
14 changes: 10 additions & 4 deletions test/2.1.x/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,19 @@ export const NumberFromString = new t.Type<number, string, unknown>(
String
)

export const HyphenatedString = new t.Type<string, string, unknown>(
'HyphenatedString',
(v): v is string => t.string.is(v) && v.length === 3 && v[1] === '-',
export const HyphenatedString = t.refinement(
t.string,
(v): v is `${string}-${string}` => v.length === 3 && v[1] === '-',
'`${string}-${string}`'
)

export const HyphenatedStringFromNonHyphenated = new t.Type<`${string}-${string}`, string, unknown>(
'HyphenatedStringFromNonHyphenated',
HyphenatedString.is,
(u, c) =>
either.chain(t.string.validate(u, c), (s) => {
if (s.length === 2) {
return right(s[0] + '-' + s[1])
return right(`${s[0]}-${s[1]}` as const)
} else {
return t.failure(s, c)
}
Expand Down
63 changes: 44 additions & 19 deletions test/2.1.x/record.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
assertStrictSuccess,
assertSuccess,
HyphenatedString,
HyphenatedStringFromNonHyphenated,
NumberFromString
} from './helpers'

Expand Down Expand Up @@ -38,6 +39,7 @@ describe.concurrent('record', () => {
const T3 = t.record(HyphenatedString, t.number)
assert.strictEqual(T3.is({}), true)
assert.strictEqual(T3.is({ 'a-a': 1 }), true)
assert.strictEqual(T3.is({ 'a-a': 1, extra: null }), true)
})

it('should return `false` on invalid inputs', () => {
Expand All @@ -54,7 +56,7 @@ describe.concurrent('record', () => {
assert.strictEqual(T2.is([]), false)

const T3 = t.record(HyphenatedString, t.number)
assert.strictEqual(T3.is({ aa: 1 }), false)
assert.strictEqual(T3.is({ 'a-a': '1' }), false)
})

it('should not accept an array if the codomain is `unknown`', () => {
Expand All @@ -69,7 +71,7 @@ describe.concurrent('record', () => {
})

describe.concurrent('decode', () => {
it('should decode a isomorphic value', () => {
it('should decode an isomorphic value', () => {
const T = t.record(t.string, t.number)
assertSuccess(T.decode({}))
assertSuccess(T.decode({ a: 1 }))
Expand All @@ -88,10 +90,17 @@ describe.concurrent('record', () => {
})

it('should decode a prismatic key', () => {
const T = t.record(HyphenatedString, t.number)
const T = t.record(HyphenatedStringFromNonHyphenated, t.number)
assertSuccess(T.decode({ ab: 1 }), { 'a-b': 1 })
})

it('should strip keys outside the domain', () => {
const T1 = t.record(HyphenatedString, t.number)
assertSuccess(T1.decode({ 'a-b': 1, extra: null }), { 'a-b': 1 })
const T2 = t.record(HyphenatedStringFromNonHyphenated, t.number)
assertSuccess(T2.decode({ ab: 1, extra: null }), { 'a-b': 1 })
})

it('should not decode an array if the codomain is `unknown`', () => {
const T = t.record(t.string, t.unknown)
assertFailure(T, [1], ['Invalid value [1] supplied to : { [K in string]: unknown }'])
Expand All @@ -111,19 +120,19 @@ describe.concurrent('record', () => {
// #407
assertFailure(T1, [1], ['Invalid value [1] supplied to : { [K in string]: number }'])
const T2 = t.record(HyphenatedString, t.number)
assertFailure(T2, { a: 1 }, [
'Invalid value "a" supplied to : { [K in HyphenatedString]: number }/a: HyphenatedString'
assertFailure(T2, { a: 1, 'a-a': '2' }, [
'Invalid value "2" supplied to : { [K in `${string}-${string}`]: number }/a-a: number'
])
})
})

describe.concurrent('encode', () => {
it('should encode a isomorphic value', () => {
it('should encode an isomorphic value', () => {
const T = t.record(t.string, t.number)
assert.deepStrictEqual(T.encode({ a: 1 }), { a: 1 })
})

it('should return the same reference while decoding a isomorphic value', () => {
it('should return the same reference while decoding an isomorphic value', () => {
const T = t.record(t.string, t.number)
const a = { a: 1 }
assert.strictEqual(T.encode(a), a)
Expand All @@ -135,10 +144,19 @@ describe.concurrent('record', () => {
})

it('should encode a prismatic key', () => {
const T = t.record(HyphenatedString, t.number)
const T = t.record(HyphenatedStringFromNonHyphenated, t.number)
assert.deepStrictEqual(T.encode({ 'a-b': 1 }), { ab: 1 })
})

it('should strip keys outside the domain', () => {
const T1 = t.record(HyphenatedString, t.number)
const withExtra1 = { 'a-b': 1, extra: null }
assert.deepStrictEqual(T1.encode(withExtra1), { 'a-b': 1 })
const T2 = t.record(HyphenatedStringFromNonHyphenated, t.number)
const withExtra2 = { 'a-b': 1, extra: null }
assert.deepStrictEqual(T2.encode(withExtra2), { ab: 1 })
})

it('should accept an array if the codomain is `any`', () => {
const T = t.record(t.string, t.any)
const a = [1]
Expand All @@ -150,19 +168,15 @@ describe.concurrent('record', () => {
const T1 = t.record(t.string, t.number)
const value1 = { aa: 1 }
assertStrictEqual(T1.decode(value1), value1)
const T2 = t.record(
t.refinement(t.string, (s) => s.length >= 2),
t.number
)
const value2 = { aa: 1 }
const T2 = t.record(HyphenatedString, t.number)
const value2 = { 'a-a': 1 }
assertStrictEqual(T2.decode(value2), value2)
})

it('should return the same reference while encoding', () => {
const T1 = t.record(t.string, t.number)
assert.strictEqual(T1.encode, t.identity)
const T2 = t.record(HyphenatedString, t.number)
assert.strictEqual(T2.encode === t.identity, false)
const T = t.record(t.string, t.number)
const value = { a: 1 }
assert.strictEqual(T.encode(value), value)
})
})

Expand Down Expand Up @@ -243,15 +257,20 @@ describe.concurrent('record', () => {
'Invalid value undefined supplied to : ({ [K in "a"]: string } & { [K in string]: unknown })/0: { [K in "a"]: string }/a: string'
])
})

it('should decode a prismatic value', () => {
const T = t.record(t.literal('a'), NumberFromString)
assertSuccess(T.decode({ a: '1' }), { a: 1 })
})
})

describe.concurrent('encode', () => {
it('should encode a isomorphic value', () => {
it('should encode an isomorphic value', () => {
const T = t.record(t.literal('a'), t.number)
assert.deepStrictEqual(T.encode({ a: 1 }), { a: 1 })
})

it('should return the same reference while decoding a isomorphic value', () => {
it('should return the same reference while decoding an isomorphic value', () => {
const T = t.record(t.literal('a'), t.number)
const a = { a: 1 }
assert.strictEqual(T.encode(a), a)
Expand All @@ -261,6 +280,12 @@ describe.concurrent('record', () => {
const T = t.record(t.literal('a'), NumberFromString)
assert.deepStrictEqual(T.encode({ a: 1 }), { a: '1' })
})

it('should strip keys outside the domain', () => {
const T = t.record(t.literal('a'), t.number)
const withExtra = { a: 1, extra: null }
assert.deepEqual(T.encode(withExtra), { a: 1 })
})
})
})
})