0.2.1 • Published 4 months ago

assert-response v0.2.1

Weekly downloads
-
License
ISC
Repository
github
Last release
4 months ago

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 (200299)

Status CodeFunction (Aliases)Negated Function (Aliases)
200ok (successful)notOk (failed)
201creatednotCreated (creationFailed)
202acceptednotAccepted (rejected)
203nonAuthoritativeInformationnotNonAuthoritativeInformation (authoritativeInformation)
204noContentnotNoContent (content)
205resetContentnotResetContent
206partialContentnotPartialContent (entireContent, fullContent)
207multiStatusnotMultiStatus (singleStatus)
208alreadyReportednotAlreadyReported
226imUsednotImUsed

Redirection Responses (300399)

Status CodeFunction (Aliases)Negated Function (Aliases)
300multipleChoicesnotMultipleChoices
301movedPermanentlynotMovedPermanently
302temporaryFound (redirect)notTemporaryFound (noRedirect)
303seeOthernotSeeOther
304notModifiedmodified
305useProxy (proxy)notUseProxy
307temporaryRedirectnotTemporaryRedirect
308permanentRedirectnotPermanentRedirect

Client Error Responses (400499)

Status CodeFunction (Aliases)Negated Function (Aliases)
400badRequest (invalid)goodRequest (valid, correct)
401unauthorizedauthorized (authenticated)
402paymentRequiredpaymentNotRequired (paymentOptional)
403forbiddennotForbidden (allowed, permitted)
404notFoundfound
405methodNotAllowedmethodAllowed
406notAcceptableacceptable
407proxyAuthRequiredproxyAuthNotRequired (proxyAuthOptional)
408requestTimeoutnotRequestTimeout (requestFast)
409conflictnotConflict (match)
410gonenotGone (present)
411lengthRequiredlengthNotRequired (lengthOptional)
412preconditionFailedpreconditionSuccessful (preconditionMet, preconditionPassed)
413payloadTooLargenotPayloadTooLarge (payloadSmall)
414uriTooLonguriNotTooLong (uriShort)
415unsupportedMediaTypesupportedMediaType
416rangeNotSatisfiablerangeSatisfiable
417expectationFailedexpectationSuccessful (expectationMet, expectationPassed)
418teapotnotTeapot
421misdirectedRequestcorrectlyDirectedRequest (directedRequest)
422unprocessableEntityprocessableEntity
423lockedunlocked (open)
424failedDependencysuccessfulDependency (dependencyMet, dependencyPassed)
425tooEarlynotTooEarly (afterSufficientTime, onTime)
426upgradeRequiredupgradeNotRequired (upgradeOptional)
428preconditionRequiredpreconditionNotRequired (preconditionOptional)
429tooManyRequestsnotTooManyRequests (fewRequests)
431requestHeaderFieldsTooLargerequestHeaderFieldsAcceptable (requestHeaderFieldsSmall)
451unavailableForLegalReasonsavailableForLegalReasons

Server Error Responses (500599)

Status CodeFunction (Aliases)Negated Function (Aliases)
500internalServerErrornoError (notInternalServerError)
501notImplementedimplemented
502badGatewaygoodGateway
503serviceUnavailableserviceAvailable
504gatewayTimeoutnotGatewayTimeout (gatewayResponsive)
505httpVersionNotSupportedhttpVersionSupported
506variantAlsoNegotiatesnotVariantAlsoNegotiates (variantNotNegotiating)
507insufficientStoragesufficientStorage (storageAvailable)
508loopDetectedloopNotDetected (noLoop)
509bandwidthLimitExceededbandwidthLimitNotExceeded (bandwidthAvailable)
510notExtendedextended
511networkAuthenticationRequirednetworkAuthenticationNotRequired (networkAuthenticationOptional)
0.2.1

4 months ago

0.2.0

4 months ago

0.1.1

5 months ago

0.1.0

5 months ago