Add valueOrError.ts

This commit is contained in:
Jerko Steiner 2019-03-27 16:17:23 +08:00
parent 58a0fb1772
commit ed047be2e3
3 changed files with 51 additions and 0 deletions

View File

@ -1,2 +1,3 @@
export * from './ErrorTransformer' export * from './ErrorTransformer'
export * from './TransformedError' export * from './TransformedError'
export * from './valueOrError'

View File

@ -0,0 +1,34 @@
import {valueOrError} from './'
describe('valueOrError', () => {
it('throws a 404 error when value is undefined', () => {
expect(() => valueOrError(undefined)).toThrowError('Not Found')
})
it('throws a 404 error when value is null', () => {
expect(() => valueOrError(null)).toThrowError('Not Found')
})
it('returns the value when it is neither null, nor undefined', () => {
const obj = {}
expect(valueOrError(obj)).toBe(obj)
expect(valueOrError(0)).toBe(0)
expect(valueOrError(1)).toBe(1)
expect(valueOrError('')).toBe('')
})
it('returns a HTTP error with custom status code', () => {
expect(() => valueOrError(undefined, 400)).toThrowError('Bad Request')
})
it('removes undefined and null from function', () => {
function getValue(): number | undefined {
return 1
}
const obj1 = getValue()
const obj2: number = valueOrError(obj1)
expect(obj2).toEqual(1)
})
})

View File

@ -0,0 +1,16 @@
import createError from 'http-errors'
/**
* Checks if the value is either null or undefined. If so, throws a Not Found
* HTTP error. Otherwise, returns the value. The parameter `statusCode` can be
* used to modify the error status code.
*/
export function valueOrError<T>(
value: T | undefined | null,
statusCode = 404,
): T {
if (value === undefined || value === null) {
throw createError(statusCode)
}
return value
}