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

🔧 Utilities

The Nodeblocks SDK provides a comprehensive set of utility functions to help you build robust, maintainable backend services. These utilities are organized by category and designed to work seamlessly with the functional programming patterns used throughout the SDK.

Import namespaces

Utilities are spread across three SDK namespaces — not everything lives under utils:

import { utils, primitives, handlers } from '@nodeblocks/backend-sdk';
NamespaceSourceCategories on this page
utilssrc/utils/*Authentication, Entity, Common, Logging, Cookie, Cache, Schema
primitivessrc/primitives/combinators.tsComposition, Handler Utilities
handlerssrc/handlers/utils.tsmergeData (used in composition pipelines)

🔐 Authentication Utilities (utils)

Comprehensive authentication and token management utilities for secure API endpoints:

  • getBearerTokenInfo: Default bearer token authentication from Authorization header
  • getCookieTokenInfo: Cookie-based token authentication for web applications
  • generateUserAccessToken: Create user access tokens with security validation
  • generateAppAccessToken: Create app access tokens for service-to-service communication
  • generateRefreshToken: Create refresh tokens for session management
  • generateOnetimeToken: Create one-time tokens for temporary access
  • decryptAndVerifyJWT: Decrypt and verify encrypted JWTs
  • tokenPassesSecurityCheck: Validate fingerprint/IP/user-agent against token
  • defaultRefreshTokenBodyAuth: Validate refresh token from request body
  • defaultRefreshTokenCookieAuth: Validate refresh token from cookies
  • resolveRefreshTokenFromRequest: Resolve refresh token from cookie and/or body
  • deriveCookieMaxAge: Convert expiresIn to cookie maxAge in milliseconds

See Authentication Utilities for the full export list.

Learn Authentication Utilities →


🆔 Entity Utilities (utils)

Essential utilities for creating and managing database entities with automatic field generation:

  • createBaseEntity: Create entities with auto-generated id, createdAt, and updatedAt fields
  • updateBaseEntity: Update entities with automatic updatedAt timestamp
  • BaseEntity: TypeScript type for the standard entity base fields

Learn Entity Utilities →


🔧 Composition Utilities (primitives)

Essential utilities for composing handlers, handling asynchronous operations, and building complex business logic pipelines:

  • compose: Combine multiple functions into a single pipeline
  • lift: Bridge an async Promise from the previous composed step to the synchronous terminator (typically orThrow)
  • flatMap: Chain synchronous operations that return Results
  • flatMapAsync: Chain asynchronous operations that return Results
  • applyPayloadArgs: Extract arguments from payload and apply to pure functions
  • orThrow: Map error types to HTTP codes and extract success data
  • match: Predicate helper for nested path checks
  • ifElse: Functional conditional for branching
  • hasValue: Non-empty predicate (not null/undefined/empty)
  • withSoftDelete: Wrap handlers to apply soft-delete filters on find/update/delete operations
  • mergeData (handlers): Merge data into the payload context for subsequent handlers
  • notFromEmitter, markAsFromEmitter: Filter and tag messages by emitter ID in RxJS/WebSocket pipelines

Additional primitives exports such as either and mapMatchingErrorToFalse are documented in Composition Utilities.

Learn Composition Utilities →


🎭 Handler Utilities (primitives)

Cross-cutting concerns and middleware-like utilities that can be applied to any handler:

  • withLogging: Add comprehensive logging to any function
  • withPagination: Add automatic pagination to MongoDB find() operations
  • withPaginatedProperty: Paginate nested arrays from findOne() results
  • DEFAULT_REDACTION: Default field redaction rules for withLogging
  • DEFAULT_SANITIZATION: Default sanitization rules for withLogging

Learn Handler Utilities →


🔧 Common Utilities (utils)

General-purpose utility functions for common operations:

  • generateUUID: Generate UUID v4 strings
  • isObject: Check if a value is an object or function (runtime check)
  • isError: Check if a value is an Error instance
  • isResult: Type guard for neverthrow Ok / Err instances

Learn Common Utilities →


📝 Logging Utilities (utils)

Pre-configured logging setup with Pino for structured logging:

  • nodeblocksLogger: Pre-configured Pino logger with pretty formatting
  • nodeblocksHTTPLogger: HTTP request/response logging middleware
  • Logger: TypeScript type alias for logger integration (pino.Logger)

Learn Logging Utilities →


Helpers for cookie-based authentication and Set-Cookie option resolution:

  • CookieOptions, DEFAULT_COOKIE_OPTS, withCookieOptDefaults, isCookieMode, whenCookieAuth

Learn Cookie Utilities →


💾 Cache Utilities (utils)

In-memory LRU cache with TTL for service-level memoization:

  • createCache: Factory with maxEntries, ttl, and get / set / del / clear / pruneExpired / size

Learn Cache Utilities →


📋 Schema Utilities (utils)

AJV schema helpers with NoSQL injection protection:

  • createAjvInstance, addMongoFilterKeyword, applySchemaDefaults, applyDefaultSchemaEnhancements

For route-level business-logic validators (distinct from schema validation), see Validator.

Learn Schema Utilities →


➡️ Next Steps