ts-http-assert
TypeScript version of http-assert with
Assertion Functions.
Motivation
There are multiple attempts to give the http-assert assertion functions supports:
All of these attemps are failed because @types/koa refers @types/http-assert as methods, and due to
https://github.com/microsoft/TypeScript/issues/36931 methods cannot simply have assertion functions.
This package is a drop-in replacement of the http-assert
package with:
- better typings, and
- assertion functions support.
Install
npm install ts-http-assert
or
yarn add ts-http-assert
Usage
Just replace all
import assert from 'http-assert'
with
import assert from 'ts-http-assert`
to give the assert
function and its child functions better typings.
-
All parameter combinations in createHttpError
, includes:
assert(value, status, message, properties)
assert(value, status, message)
assert(value, status, properties)
assert(value, status)
assert(value, message, properties)
assert(value, message)
assert(value, properties)
assert(value)
-
assert
and assert.ok
have assertion signatures to assert the condition is true,
for example:
import { IncomingMessage, ServerResponse } from 'http'
import assert from 'ts-http-assert'
function controller(req: IncomingMessage, res: ServerResponse): void {
const authorization = req.headers['authorization']
assert(typeof authorization === 'string', 401)
const [method, credentials] = authorization.split(' ', 2)
res.end(`You are in ${method} authorization.`)
}
-
assert.strictEqual
has assertion signature to assert to 2 values are of the same type,
for example:
import { IncomingMessage, ServerResponse } from 'http'
import assert from 'ts-http-assert'
function controller(req: IncomingMessage, res: ServerResponse): void {
const contentType = req.headers['content-type']
assert.strictEqual(contentType, 'application/json')
res.end(`You submitted in type ${contentType.splice('/')[1]}`)
}
License
MIT