Add valueOrError.ts
This commit is contained in:
parent
58a0fb1772
commit
ed047be2e3
@ -1,2 +1,3 @@
|
||||
export * from './ErrorTransformer'
|
||||
export * from './TransformedError'
|
||||
export * from './valueOrError'
|
||||
|
||||
34
packages/server/src/error/valueOrError.test.ts
Normal file
34
packages/server/src/error/valueOrError.test.ts
Normal 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)
|
||||
})
|
||||
|
||||
})
|
||||
16
packages/server/src/error/valueOrError.ts
Normal file
16
packages/server/src/error/valueOrError.ts
Normal 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
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user