メインコンテンツまでスキップ
バージョン: 🚧 Canary

🧩 Common Blocks

Common blocks provide reusable building blocks that can be used across domains. This page documents utility blocks that are not specific to a single entity domain.


🎯 Overview

Common blocks are designed to:

  • Encapsulate reusable logic used across multiple flows
  • Standardize behavior (e.g., redirects, password generation)
  • Improve composability in route and feature chains

📋 Available Common Blocks

redirectTo

Redirects HTTP response to specified URL with optional status code.

Purpose: Finalizes flows by issuing an HTTP redirect.

Parameters:

  • response: Response — Express response object for HTTP redirection
  • url: string — Target URL to redirect to
  • statusCode?: number — Optional HTTP status code (defaults to 302)

Returns: Result<void, Error>

Handler Process:

  • Input: Express response object, target URL, and optional status code
  • Process: Calls Express response.redirect(statusCode, url)
  • Output: Result<void, Error> indicating redirect completion
  • Errors: Propagates errors from Express redirect if any occur

Example Usage:

// Used in route composition (inject response and URL from context/data):
const redirectRoute = withRoute({
handler: compose(
applyPayloadArgs(redirectTo, [
['context', 'response'],
['context', 'data', 'redirectUrl'],
// optional: provide status code if needed
// ['params', 'requestQuery', 'statusCode']
])
)
});

generateRandomPassword

Generates cryptographically secure random password with specified length.

Purpose: Produce secure random passwords for initial credentials or resets.

Parameters:

  • length?: number — Optional password length (defaults to 16)

Returns: string

Handler Process:

  • Input: Optional password length (defaults to 16 characters)
  • Process: Uses crypto.randomBytes and maps output to a mixed character set
  • Output: String containing a random password of the specified length
  • Errors: None (uses cryptographically secure random generation)

Example Usage:

// Generate default 16-character password:
const password = generateRandomPassword();

// Generate custom length password:
const longPassword = generateRandomPassword(32);

normalizeRawDocument

Raw document normalization utility removing MongoDB _id field.

Purpose: Removes MongoDB internal _id field from database documents before API responses.

Handler process:

  • Input: Document object containing arbitrary fields and optional _id
  • Process: Omits _id from the provided raw database document
  • Output: Returns ok({...documentWithoutId}) as a Result
  • Errors: None; always resolves to ok

Parameters:

  • document: Record<string, unknown> & { _id?: string } - Record of document properties with optional _id string

Returns: Result<Record<string, unknown>, never> with the document fields excluding _id

Example Usage:

import { blocks } from '@nodeblocks/backend-sdk';

const result = blocks.normalizeRawDocument({
_id: '507f1f77bcf86cd799439011',
name: 'Acme',
field2: true
});
// result.unwrap() -> { name: 'Acme', field2: true }

normalizeDocuments

Normalizes an array of raw documents by removing MongoDB _id fields from each document.

Purpose: Removes MongoDB internal _id field from multiple database documents before API responses.

Handler process:

  • Input: Array of document objects containing arbitrary fields and optional _id
  • Process: Maps over each document using normalizeRawDocument to remove _id fields
  • Output: Returns Result.combine() with array of normalized documents
  • Errors: None; always resolves to ok with normalized document array

Parameters:

  • documents: Record<string, unknown>[] - Array of document records with optional _id strings

Returns: Result<Record<string, unknown>[], never> with array of documents excluding _id fields

Example Usage:

import { blocks } from '@nodeblocks/backend-sdk';

const rawDocs = [
{ _id: '64f1', name: 'Acme Corp' },
{ _id: '64f2', name: 'Tech Inc' }
];
const result = blocks.normalizeDocuments(rawDocs);
// result.unwrap() -> [{ name: 'Acme Corp' }, { name: 'Tech Inc' }]

normalizeEmptyBody

Normalizes empty response body for API handlers.

Purpose: Standardizes empty API responses by returning a consistent empty object.

Parameters: None

Returns: object — Always returns an empty object {}

Handler Process:

  • Input: No parameters required
  • Process: Returns an empty object to standardize empty API responses
  • Output: Returns an empty object {}
  • Errors: No errors expected (always returns empty object)

Example Usage:

// Used in route handler chains to ensure a consistent empty response body:
const route = withRoute({
handler: compose(
// ... perform operations that don't need response data
applyPayloadArgs(normalizeEmptyBody, [], 'normalizedBody'),
lift(orThrow([...], [['context', 'data', 'normalizedBody'], 204]))
)
});