A lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.
npm install assert-responseA lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.
If the resource is missing, throw a 404 Not Found response.
``ts
import { found } from "assert-response";
function loader() {
const foo = getFoo(); // Foo | undefined
// Throws a 404 response if foo is undefined
found(foo);
foo; // Type is now Foo
// Do something with foo
}
`
If the user is not authenticated, throw a 401 Unauthorized response.
`ts
import { authorized } from "assert-response";
function action() {
const user = getCurrentUser(); // User | null
// Throws a 401 response if user is null
authorized(user);
user; // Type is now User
// ...
}
`
If the operation was unsuccessful, throw a 500 Internal Server Error.
`ts
import { noError } from "assert-response";
function action() {
const success = processRequest(); // boolean
// Throws a 500 response if success is false
noError(success);
// Do further actions
}
`
If the operation was successful, throw a 200 OK.
`ts
import { internalServerError, notOk } from "assert-response";
function action() {
const [error] = processOtherRequest(); // [string | null]
// Throws a 200 response if error is null
notOk(error);
error; // Type is now string
console.error(error);
// Throws a 500 response if error is not null
internalServerError(error);
}
`
This example ensures:
- 👋 The user is authenticated (401 Unauthorized).403 Forbidden
- 🔓 The user has permission to update the document ().400 Bad Request
- ✅ The input is valid ().404 Not Found
- 🔍 The document exists ().409 Conflict
- 🤝 The document has not been modified since the last retrieval ().500 Internal Server Error
- ⚠️ / 👌 The update is successful ( / 204 No Content).
`ts
import {
authorized,
allowed,
found,
match,
noContent,
valid,
internalServerError,
} from "assert-response";
interface Document {
id: string;
lastModified: number;
}
async function saveAndContinueEditing(doc?: Document) {
const user = getCurrentUser();
// 👋 Throws a 401 response if current user is null
authorized(user, "Authentication required");
user; // Type is now User
// 🔓 Throws a 403 response if not permitted
allowed(
user.permissions.includes("update-document"),
"Permission to update document required"
);
// ✅ Throws a 400 response if missing update document
valid(doc, "Missing document");
doc; // Type is now Document
const prevDoc: Document | undefined = await database.find(doc.id);
// 🔍 Throws a 404 response if the document does not exist
found(prevDoc, "Document not found");
prevDoc; // Type is now Document
// 🤝 Throws a 409 response if the document has been modified since last retrieval
match(prevDoc.lastModified === doc.lastModified, "Conflict detected");
const [error] = await database.put(doc);
// ⚠️ Throws a 500 response if the update failed
internalServerError(error);
// 👌 Throws a 204 response if everything successful
noContent(true);
}
`
---
Each assertion function checks a condition and throws a Response with the corresponding HTTP status code if the condition is truthy.
Negated functions work in reverse: they throw a response when the condition is falsy.
You may also pass an optional body and options parameters for Response as the second and third arguments for the assertion function. These can either be values or functions that return the respective values.
To use these functions:
`ts
import { found, ok, redirect, valid } from "assert-response";
// Throws a 200 response if user is truthy, with a dynamic message
ok(
user,
() => JSON.stringify({ message: "Welcome back!" }),
() => ({ headers: { "Content-Type": "application/json" } })
);
// Throws a 302 response with options if redirectURL is set
redirect(redirectURL, undefined, {
headers: {
Location: redirectURL!,
},
});
// Validate user input (Negated function, throws 400 response if condition is falsy)
valid(isValid(input), "Invalid input");
// Ensure item is found (Negated function, throws 404 response if condition is falsy)
found(item, "Item not found");
`
Each function is mapped to an HTTP status code.
#### Successful Responses (200–299)
| Status Code | Function _(Aliases)_ | Negated Function _(Aliases)_ |
| ------------------------------------------------------------- | ----------------------------- | -------------------------------------------------------------------- |
| 200 | ok successful
_()_ | notOk failed
_()_ |created
| 201 | | notCreated creationFailed
_()_ |accepted
| 202 | | notAccepted rejected
_()_ |nonAuthoritativeInformation
| 203 | | notNonAuthoritativeInformation authoritativeInformation
_()_ |noContent
| 204 | | notNoContent content
_()_ |resetContent
| 205 | | notResetContent |partialContent
| 206 | | notPartialContent entireContent
_(, fullContent)_ |multiStatus
| 207 | | notMultiStatus singleStatus
_()_ |alreadyReported
| 208 | | notAlreadyReported |imUsed
| 226 | | notImUsed |
#### Redirection Responses (300–399)
| Status Code | Function _(Aliases)_ | Negated Function _(Aliases)_ |
| ------------------------------------------------------------- | ------------------------------------ | ----------------------------------------- |
| 300 | multipleChoices | notMultipleChoices |movedPermanently
| 301 | | notMovedPermanently |temporaryFound
| 302 | redirect
_()_ | notTemporaryFound noRedirect
_()_ |seeOther
| 303 | | notSeeOther |notModified
| 304 | | modified |useProxy
| 305 | proxy
_()_ | notUseProxy |temporaryRedirect
| 307 | | notTemporaryRedirect |permanentRedirect
| 308 | | notPermanentRedirect |
#### Client Error Responses (400–499)
| Status Code | Function _(Aliases)_ | Negated Function _(Aliases)_ |
| ------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------- |
| 400 | badRequest invalid
_()_ | goodRequest valid
_(, correct)_ |unauthorized
| 401 | | authorized authenticated
_()_ |paymentRequired
| 402 | | paymentNotRequired paymentOptional
_()_ |forbidden
| 403 | | notForbidden allowed
_(, permitted)_ |notFound
| 404 | | found |methodNotAllowed
| 405 | | methodAllowed |notAcceptable
| 406 | | acceptable |proxyAuthRequired
| 407 | | proxyAuthNotRequired proxyAuthOptional
_()_ |requestTimeout
| 408 | | notRequestTimeout requestFast
_()_ |conflict
| 409 | | notConflict match
_()_ |gone
| 410 | | notGone present
_()_ |lengthRequired
| 411 | | lengthNotRequired lengthOptional
_()_ |preconditionFailed
| 412 | | preconditionSuccessful preconditionMet
_(, preconditionPassed)_ |payloadTooLarge
| 413 | | notPayloadTooLarge payloadSmall
_()_ |uriTooLong
| 414 | | uriNotTooLong uriShort
_()_ |unsupportedMediaType
| 415 | | supportedMediaType |rangeNotSatisfiable
| 416 | | rangeSatisfiable |expectationFailed
| 417 | | expectationSuccessful expectationMet
_(, expectationPassed)_ |teapot
| 418 | | notTeapot |misdirectedRequest
| 421 | | correctlyDirectedRequest directedRequest
_()_ |unprocessableEntity
| 422 | | processableEntity |locked
| 423 | | unlocked open
_()_ |failedDependency
| 424 | | successfulDependency dependencyMet
_(, dependencyPassed)_ |tooEarly
| 425 | | notTooEarly afterSufficientTime
_(, onTime)_ |upgradeRequired
| 426 | | upgradeNotRequired upgradeOptional
_()_ |preconditionRequired
| 428 | | preconditionNotRequired preconditionOptional
_()_ |tooManyRequests
| 429 | | notTooManyRequests fewRequests
_()_ |requestHeaderFieldsTooLarge
| 431 | | requestHeaderFieldsAcceptable requestHeaderFieldsSmall
_()_ |unavailableForLegalReasons
| 451 | | availableForLegalReasons |
#### Server Error Responses (500–599)
| Status Code | Function _(Aliases)_ | Negated Function _(Aliases)_ |
| ------------------------------------------------------------- | ------------------------------- | --------------------------------------------------------------------------- |
| 500 | internalServerError | noError notInternalServerError
_()_ |notImplemented
| 501 | | implemented |badGateway
| 502 | | goodGateway |serviceUnavailable
| 503 | | serviceAvailable |gatewayTimeout
| 504 | | notGatewayTimeout gatewayResponsive
_()_ |httpVersionNotSupported
| 505 | | httpVersionSupported |variantAlsoNegotiates
| 506 | | notVariantAlsoNegotiates variantNotNegotiating
_()_ |insufficientStorage
| 507 | | sufficientStorage storageAvailable
_()_ |loopDetected
| 508 | | loopNotDetected noLoop
_()_ |bandwidthLimitExceeded
| 509 | | bandwidthLimitNotExceeded bandwidthAvailable
_()_ |notExtended
| 510 | | extended |networkAuthenticationRequired
| 511 | | networkAuthenticationNotRequired networkAuthenticationOptional`)_ |
_(