diff --git a/sanitizers/src/asNullable.ts b/sanitizers/src/asNullable.ts new file mode 100644 index 0000000..59f5a1f --- /dev/null +++ b/sanitizers/src/asNullable.ts @@ -0,0 +1,8 @@ +import { Sanitizer, Result } from "."; + +export const asNullable = (sanitizer: Sanitizer) : Sanitizer => + (value, path) => value === null + ? Result.ok(null) + : value === undefined + ? Result.error([{ path, expected: 'not undefined' }]) + : sanitizer(value, path) diff --git a/sanitizers/src/index.ts b/sanitizers/src/index.ts index 7353099..b79cfd4 100644 --- a/sanitizers/src/index.ts +++ b/sanitizers/src/index.ts @@ -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' diff --git a/sanitizers/test/asNullable.test.ts b/sanitizers/test/asNullable.test.ts new file mode 100644 index 0000000..9eb57ac --- /dev/null +++ b/sanitizers/test/asNullable.test.ts @@ -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)) + }) +}); \ No newline at end of file