Skip to content

A lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.

Notifications You must be signed in to change notification settings

ArnoSaine/assert-response

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

assert-response

A lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.

Usage

Ensure a resource exists

If the resource is missing, throw a 404 Not Found response.

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
}

Require authentication

If the user is not authenticated, throw a 401 Unauthorized response.

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
  // ...
}

Validate a successful operation

If the operation was unsuccessful, throw a 500 Internal Server Error.

import { noError } from "assert-response";

function action() {
  const success = processRequest(); // boolean

  // Throws a 500 response if success is false
  noError(success);
  // Do further actions
}

Validate an unsuccessful operation

If the operation was successful, throw a 200 OK.

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);
}

Validate permissions and resource conflicts before saving

This example ensures:

  • πŸ‘‹ The user is authenticated (401 Unauthorized).
  • πŸ”“ The user has permission to update the document (403 Forbidden).
  • βœ… The input is valid (400 Bad Request).
  • πŸ” The document exists (404 Not Found).
  • 🀝 The document has not been modified since the last retrieval (409 Conflict).
  • ⚠️ / πŸ‘Œ The update is successful (500 Internal Server Error / 204 No Content).
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);
}

API

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:

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");

Assertion Functions

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)
201 created notCreated
(creationFailed)
202 accepted notAccepted
(rejected)
203 nonAuthoritativeInformation notNonAuthoritativeInformation
(authoritativeInformation)
204 noContent notNoContent
(content)
205 resetContent notResetContent
206 partialContent notPartialContent
(entireContent, fullContent)
207 multiStatus notMultiStatus
(singleStatus)
208 alreadyReported notAlreadyReported
226 imUsed notImUsed

Redirection Responses (300–399)

Status Code Function (Aliases) Negated Function (Aliases)
300 multipleChoices notMultipleChoices
301 movedPermanently notMovedPermanently
302 temporaryFound
(redirect)
notTemporaryFound
(noRedirect)
303 seeOther notSeeOther
304 notModified modified
305 useProxy
(proxy)
notUseProxy
307 temporaryRedirect notTemporaryRedirect
308 permanentRedirect notPermanentRedirect

Client Error Responses (400–499)

Status Code Function (Aliases) Negated Function (Aliases)
400 badRequest
(invalid)
goodRequest
(valid, correct)
401 unauthorized authorized
(authenticated)
402 paymentRequired paymentNotRequired
(paymentOptional)
403 forbidden notForbidden
(allowed, permitted)
404 notFound found
405 methodNotAllowed methodAllowed
406 notAcceptable acceptable
407 proxyAuthRequired proxyAuthNotRequired
(proxyAuthOptional)
408 requestTimeout notRequestTimeout
(requestFast)
409 conflict notConflict
(match)
410 gone notGone
(present)
411 lengthRequired lengthNotRequired
(lengthOptional)
412 preconditionFailed preconditionSuccessful
(preconditionMet, preconditionPassed)
413 payloadTooLarge notPayloadTooLarge
(payloadSmall)
414 uriTooLong uriNotTooLong
(uriShort)
415 unsupportedMediaType supportedMediaType
416 rangeNotSatisfiable rangeSatisfiable
417 expectationFailed expectationSuccessful
(expectationMet, expectationPassed)
418 teapot notTeapot
421 misdirectedRequest correctlyDirectedRequest
(directedRequest)
422 unprocessableEntity processableEntity
423 locked unlocked
(open)
424 failedDependency successfulDependency
(dependencyMet, dependencyPassed)
425 tooEarly notTooEarly
(afterSufficientTime, onTime)
426 upgradeRequired upgradeNotRequired
(upgradeOptional)
428 preconditionRequired preconditionNotRequired
(preconditionOptional)
429 tooManyRequests notTooManyRequests
(fewRequests)
431 requestHeaderFieldsTooLarge requestHeaderFieldsAcceptable
(requestHeaderFieldsSmall)
451 unavailableForLegalReasons availableForLegalReasons

Server Error Responses (500–599)

Status Code Function (Aliases) Negated Function (Aliases)
500 internalServerError noError
(notInternalServerError)
501 notImplemented implemented
502 badGateway goodGateway
503 serviceUnavailable serviceAvailable
504 gatewayTimeout notGatewayTimeout
(gatewayResponsive)
505 httpVersionNotSupported httpVersionSupported
506 variantAlsoNegotiates notVariantAlsoNegotiates
(variantNotNegotiating)
507 insufficientStorage sufficientStorage
(storageAvailable)
508 loopDetected loopNotDetected
(noLoop)
509 bandwidthLimitExceeded bandwidthLimitNotExceeded
(bandwidthAvailable)
510 notExtended extended
511 networkAuthenticationRequired networkAuthenticationNotRequired
(networkAuthenticationOptional)

About

A lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •