Skip to content
Open
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
8 changes: 8 additions & 0 deletions sanitizers/src/asNullable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Sanitizer, Result } from ".";

export const asNullable = <T>(sanitizer: Sanitizer<T>) : Sanitizer<T | null> =>
(value, path) => value === null
? Result.ok(null)
: value === undefined
? Result.error([{ path: 'path', expected: 'not undefined' }])
: sanitizer(value, path)
1 change: 1 addition & 0 deletions sanitizers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export { asFlatMapped } from './asFlatMapped'
export { asInteger } from './asInteger'
export { asMapped } from './asMapped'
export { asMatching } from './asMatching'
export { asNullable } from './asNullable'
export { asNumber } from './asNumber'
export { asObject } from './asObject'
export { asOptional } from './asOptional'
Expand Down
33 changes: 33 additions & 0 deletions sanitizers/test/asNullable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { expect } from 'chai'
import { asString, asNullable, Result } from '../src';


describe('asNullable', () => {
it('sanitizes using the nested sanitizer', async () => {
const asNullableString = asNullable(asString)
const result = asNullableString('abc', '')
expect(result).to.deep.equal(Result.ok('abc'))
})

it('returns nested sanitizer errors', async () => {
const asNullableString = asNullable(asString)
const result = asNullableString(false, 'path')
expect(result).to.deep.equal(
Result.error([{ path: 'path', expected: 'string' }])
)
})

it('sanitizes undefined', async () => {
const asNullableString = asNullable(asString)
const result = asNullableString(undefined, 'path')
expect(result).to.deep.equal(
Result.error([{ path: 'path', expected: 'not undefined' }])
)
})

it('sanitizes null', async () => {
const asNullableString = asNullable(asString)
const result = asNullableString(null, 'path')
expect(result).to.deep.equal(Result.ok(null))
})
});