Skip to content

Commit

Permalink
feat(validathor): add tuple schema
Browse files Browse the repository at this point in the history
  • Loading branch information
Kosai106 committed Jul 30, 2024
1 parent 51d34a6 commit b39fbab
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
34 changes: 34 additions & 0 deletions packages/validathor/src/schemas/__tests__/tuple.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { parse } from '@/core/parse'
import { max } from '@/modifiers'
import { string, number, boolean } from '@/schemas'

import { tuple } from '../tuple'

describe('tuple()', () => {
it('should be named correctly', () => {
expect(tuple([number()]).name).toEqual('tuple')
})

it.each([
[
[number(), string()],
[123, 'hello'],
],
[
[boolean(), number()],
[true, 456],
],
])('should work', (schema, input) => {
const tupleSchema = tuple(schema)

expect(parse(tupleSchema, input)).toEqual(input)
})

it('should fail', () => {
const schema1 = tuple([number(), string()])
const schema2 = tuple([number([max(10)]), string()])

expect(() => parse(schema1, ['hello', true])).toThrowError()
expect(() => parse(schema2, [69, 'hello'])).toThrowError()
})
})
27 changes: 27 additions & 0 deletions packages/validathor/src/schemas/tuple.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { Parser } from '@/types'
import { assert, TypeError } from '@/utils'
import { ERROR_CODES } from '@/utils/errors/errorCodes'

export const tuple = <T extends Parser<unknown>[]>(
schema: T,
message?: {
type_error?: string
},
): Parser<T[]> => ({
name: 'tuple' as const,
parse: (value: unknown): T[] => {
assert(
Array.isArray(value),
new TypeError(message?.type_error || ERROR_CODES.ERR_TYP_0000.message()),
)

assert(
value.length === schema.length,
new TypeError(
ERROR_CODES.ERR_TYP_0000.message(message?.type_error || 'Tuple length mismatch'),
),
)

return value.map((item, index) => schema[index].parse(item)) as T[]
},
})

0 comments on commit b39fbab

Please sign in to comment.