🔧 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';
| Namespace | Source | Categories on this page |
|---|---|---|
utils | src/utils/* | Authentication, Entity, Common, Logging, Cookie, Cache, Schema |
primitives | src/primitives/combinators.ts | Composition, Handler Utilities |
handlers | src/handlers/utils.ts | mergeData (used in composition pipelines) |
🔐 Authentication Utilities (utils)
Comprehensive authentication and token management utilities for secure API endpoints:
getBearerTokenInfo: Default bearer token authentication from Authorization headergetCookieTokenInfo: Cookie-based token authentication for web applicationsgenerateUserAccessToken: Create user access tokens with security validationgenerateAppAccessToken: Create app access tokens for service-to-service communicationgenerateRefreshToken: Create refresh tokens for session managementgenerateOnetimeToken: Create one-time tokens for temporary accessdecryptAndVerifyJWT: Decrypt and verify encrypted JWTstokenPassesSecurityCheck: Validate fingerprint/IP/user-agent against tokendefaultRefreshTokenBodyAuth: Validate refresh token from request bodydefaultRefreshTokenCookieAuth: Validate refresh token from cookiesresolveRefreshTokenFromRequest: Resolve refresh token from cookie and/or bodyderiveCookieMaxAge: ConvertexpiresInto cookiemaxAgein 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-generatedid,createdAt, andupdatedAtfieldsupdateBaseEntity: Update entities with automaticupdatedAttimestampBaseEntity: TypeScript type for the standard entity base fields
🔧 Composition Utilities (primitives)
Essential utilities for composing handlers, handling asynchronous operations, and building complex business logic pipelines:
compose: Combine multiple functions into a single pipelinelift: Bridge an asyncPromisefrom the previous composed step to the synchronous terminator (typicallyorThrow)flatMap: Chain synchronous operations that return ResultsflatMapAsync: Chain asynchronous operations that return ResultsapplyPayloadArgs: Extract arguments from payload and apply to pure functionsorThrow: Map error types to HTTP codes and extract success datamatch: Predicate helper for nested path checksifElse: Functional conditional for branchinghasValue: Non-empty predicate (not null/undefined/empty)withSoftDelete: Wrap handlers to apply soft-delete filters on find/update/delete operationsmergeData(handlers): Merge data into the payload context for subsequent handlersnotFromEmitter,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.
🎭 Handler Utilities (primitives)
Cross-cutting concerns and middleware-like utilities that can be applied to any handler:
withLogging: Add comprehensive logging to any functionwithPagination: Add automatic pagination to MongoDBfind()operationswithPaginatedProperty: Paginate nested arrays fromfindOne()resultsDEFAULT_REDACTION: Default field redaction rules forwithLoggingDEFAULT_SANITIZATION: Default sanitization rules forwithLogging
🔧 Common Utilities (utils)
General-purpose utility functions for common operations:
generateUUID: Generate UUID v4 stringsisObject: Check if a value is an object or function (runtime check)isError: Check if a value is anErrorinstanceisResult: Type guard forneverthrowOk/Errinstances
📝 Logging Utilities (utils)
Pre-configured logging setup with Pino for structured logging:
nodeblocksLogger: Pre-configured Pino logger with pretty formattingnodeblocksHTTPLogger: HTTP request/response logging middlewareLogger: TypeScript type alias for logger integration (pino.Logger)
🍪 Cookie Utilities (utils)
Helpers for cookie-based authentication and Set-Cookie option resolution:
CookieOptions,DEFAULT_COOKIE_OPTS,withCookieOptDefaults,isCookieMode,whenCookieAuth
💾 Cache Utilities (utils)
In-memory LRU cache with TTL for service-level memoization:
createCache: Factory withmaxEntries,ttl, andget/set/del/clear/pruneExpired/size
📋 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.
➡️ Next Steps
- Check out Concepts for the underlying principles
- Explore Authentication Utilities for token management and security patterns
- See Authentication Service for service-level auth configuration