Skip to main content

Server-side utilities

caution

Prior to the library v1.47.0-alpha.8 all these utilities were exported as fields and methods of the server function, exported from the main library export; starting with v1.47.0-alpha.8 they are moved to separate exports from the dedicated server-side package export @dr.pogodin/react-utils/server.

Constants

  • CODES — A map from HTTP status code names to the corresponding numeric codes.
  • ERRORS — A map from HTTP status code names to their pretty-printed names.
  • SCRIPT_LOCATIONS — The map of valid location values in Script objects.

Functions

Deprecated
  • errors.joi — Removed in v1.44.0; an alias for Joi library, which provides methods for HTTP request validation.

Constants

CODES

import { CODES } from '@dr.pogodin/react-utils/server';

enum CODES {
// Same as StatusCodes from 'http-status-codes'.
}

Enum of HTTP status codes — an alias of StatusCodes enum from the http-status-codes library.

Example

import { CODES } from '@dr.pogodin/react-utils/server';

console.log(CODES.BAD_REQUEST);

// Prints: 400

ERRORS

import { ERRORS } from '@dr.pogodin/react-utils/server';

ERRORS: object

A map from HTTP status code names to their pretty-printed names. It is an alias for ReasonPhrases object from http-status-codes library.

Example

import { ERRORS } from '@dr.pogodin/react-utils/server';

console.log(ERRORS.BAD_REQUEST);

// Prints: Bad Request

SCRIPT_LOCATIONS

import { SCRIPT_LOCATIONS } from '@dr.pogodin/react-utils/server';

SCRIPT_LOCATIONS: object

This object provides the map of valid Script's location values:

  • BODY_OPEN - Right after the opening <body> tag.
  • DEFAULT - In the end of <body> tag, just before the main application bundle. This is the default location where scripts are injected when provided as strings rather than Script objects.
  • HEAD_OPEN - Right after the opening <head> tag.

Functions

assert()

import { assert, CODES } from '@dr.pogodin/react-utils/server';

async function assert<T extends StandardSchemaV1>(
value: unknown,
schema: T,
message = '',
statusCode = CODES.BAD_REQUEST, // 400
): Promise<StandardSchemaV1.InferOutput<T>>;

Validates the value against the given validation schema, compliant to the Standard Schema Specs, e.g. Zod (recommended), or Joi, etc.. Throws an error with the given error message and statusCode if the validation fails, otherwise resolves to the validated value.

Arguments

  • valueunknown — The value to validate.
  • schemaStandardSchemaV1 — The validation schema, compliant to the Standard Schema Specs.
  • message = ''string — Optional. Error message. If given, the error message from the validator will be appended to it, otherwise the error message from the validator is used as is.
  • statusCode = 400number — Optional. Error status code. Defaults 400 (bad request).

Resolves the validated value, with correctly inferred type.

fail()

import { CODES, fail } from '@dr.pogodin/react-utils/server';

function fail(
message: string,
statusCode: CODES = CODES.INTERNAL_SERVER_ERROR,
): Error;

Throws an error with the given message and HTTP statusCode.

Arguments

  • messagestring — Error message.
  • statusCodeCODES — Optional. HTTP status code. Defaults 500 (internal server error).

It never returns; however, its return type is declared as Error to allow throw fail(..), thus allowing the following TypeScript code:

const value: number | undefined = someFunction();
if (value === undefined) throw fail('Some error');

// TypeScript allows this, because `throw fail()` above narrows down
// the `value` down to just `number`.
const nextValue = value + 1;

// NOTE: According to TypeScript documentation it seems that `never` return
// type would be more appropriate for `fail()`; however, `never` return type
// does not result in the same value type narrowing in this example.

getErrorForCode()

import { getErrorForCode } from '@dr.pogodin/react-utils/server';

function getErrorForCode(code): string

Given HTTP status code returns the corresponding error text. It is an alias for getReasonPhrase() function from http-status-codes library.

Arguments & Result

  • code - number - HTTP status code.
  • Returns string - Error message.

newError()

import { newError } from '@dr.pogodin/react-utils/server';

function newError(message, statusCode = 500): Error

Creates a new Error object with given message, and HTTP statusCode attached to the result as result.status field.

Arguments & Result

  • message - string - Error message.
  • statusCode = 500 - number - Optional. HTTP status code. Defaults 500 (Internal Server Error).
  • Returns Error.

getDefaultCspSettings()

import { getDefaultCspSettings } from '@dr.pogodin/react-utils/server';

getDefaultCspSettings(): object

Returns a deep copy of default CSP settings object used by react-utils, with exception of nonce-xxx clause in script-src directive, which is added dynamically for each request.

registerBabelLoader()

import { registerBabelLoader } from '@dr.pogodin/react-utils/server';

function registerBabelLoader(options: RegisterBabelLoaderArgT = {}): void

// where
type RegisterBabelLoaderArgT = {
envName?: string;
root?: string;
};

Registers a Node module API hook that customizes ES module loading to run Babel transformation on .js, .jsx, .svg, .ts, and .tsx modules, located outside node_modules and config/babel folders. It is essentially the same feature provided by @babel/node, and @babel/register, that do not work with imported ES modules as of Babel v8.

It is intended for development (test) environment purposes, as it does the transformation “on the fly”, and caches transformation results in memory.

BEWARE

It depends on '@babel/core', which is declared as development-only dependency of this library.

Options:

  • envNamestring — Babel environment. Defaults development.
  • rootstring — Babel root. Defaults the current working directory.

registerResolver()

import { registerResolver } from '@dr.pogodin/react-utils/server';

function registerResolver(): void;

Registers a Node module API hook that customizes ES module resolution to make mandatory file extensions optional.

More specifically, it intercepts module resolution requests with import condition, and relative import specifiers (those starting with . or /), and attempts to resolve them by appending .js, .jsx, .ts, and .tsx extensions; and if the given specifier points to a directory, it attempts to resolve it by appending /index.js, /index.jsx, /index.ts, and /index.tsx.

errors.joi

Deprecated

Removed in v1.44.0. The original documentation below is kept for reference.


server.errors.joi: object

An alias for Joi library, which provides methods useful for HTTP request validation.

Example: Joi methods are used to create validation schema for the body of a sample HTTP request.

import { server } from '@dr.pogodin/react-utils';

const { joi } = server.errors;
const requestBodySchema = joi.object({
sampleKey: joi.string().max(16).required(),
});