UNPKG

@catbee/utils

Version:

A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.

266 lines (261 loc) 9.55 kB
/* * The MIT License * * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import { Request } from 'express'; import { WithPagination as WithPagination$1 } from '@catbee/utils/response'; /** * Options for parsing and validating request parameters. */ interface ValidationOptions { /** Whether to throw an error on validation failure */ throwOnError?: boolean; /** Custom error message for validation failures */ errorMessage?: string; /** Default value to use if parameter is missing */ defaultValue?: any; /** Whether the parameter is required */ required?: boolean; } /** * Result of a parameter validation operation. */ interface ValidationResult<T> { /** Whether validation was successful */ isValid: boolean; /** The validated and potentially transformed value */ value: T | null; /** Error message if validation failed */ error?: string; } /** * Extracts pagination, sorting, and optional search params from a request. * * @param req - Express request * @returns Object containing validated pagination, sorting, and additional query params */ declare const getPaginationParams: <T = {}>(req: Request) => WithPagination$1<T>; /** * Safely parses a string parameter to a number. * * @param value - String value to parse * @param options - Validation options * @returns Validation result containing the parsed number or error */ declare function parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>; /** * Safely parses a string parameter to a boolean. * * @param value - String value to parse * @param options - Validation options * @returns Validation result containing the parsed boolean or error */ declare function parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>; /** * Extracts pagination parameters from request query parameters. * * @param query - Query parameters object * @param defaultPage - Default page number if not specified (defaults to 1) * @param defaultLimit - Default per page size if not specified (defaults to 20) * @param maxLimitSize - Maximum allowed per page size (defaults to 100) * @returns Object containing validated page and limit */ declare function extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): { page: number; limit: number; }; /** * Extracts sorting parameters from request query parameters. * * @param query - Query parameters object * @param allowedFields - Array of field names that are allowed to be sorted * @param defaultSort - Default sort configuration if not specified * @returns Object containing sort field and direction */ declare function extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?: { sortBy: string; sortOrder: 'asc' | 'desc'; }): { sortBy: string; sortOrder: 'asc' | 'desc'; }; /** * Extracts filter parameters from query parameters based on allowed filter fields. * * @param query - Query parameters object * @param allowedFilters - Array of field names that are allowed to be used as filters * @returns Object containing the filters as key-value pairs */ declare function extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>; /** * Generic API response format. * Used to wrap any successful or failed response from the server. */ interface ApiResponse<T = any> { /** Payload returned from the API. Can be any shape depending on the endpoint. */ data: T | null; /** Indicates whether an error occurred (true = error, false = success). */ error: boolean; /** Success message describing the result of the operation. */ message: string; /** Unique request ID for traceability in logs (e.g., from a middleware). */ requestId: string; /** ISO timestamp when the response was generated. */ timestamp: string; } /** * Generic pagination structure used for paged lists (e.g., /users?page=1). */ interface Pagination<T = any> { /** List of records for the current page. */ content: T[]; /** Metadata about the pagination state. */ pagination: { /** Total number of records across all pages. */ totalRecords: number; /** Total number of pages available. */ totalPages: number; /** Current page number (1-based index). */ page: number; /** Number of records per page. */ limit: number; /** Field by which the data is sorted. */ sortBy: string; /** Sort order: ascending or descending. */ sortOrder: 'asc' | 'desc'; }; } /** * Alias for paginated API response. * Allows semantic naming like `PaginationResponse<User>` or `PaginationResponse<Post>`. */ type PaginationResponse<T = any> = Pagination<T>; /** * Error response structure with additional metadata. * Used for providing richer error information to clients. */ interface ApiErrorResponse extends Omit<ApiResponse<never>, 'data'> { /** Error always true for error responses */ error: true; /** HTTP status code */ status: number; /** Path to the resource that caused the error */ path: string; /** Stack trace of the error (if available) */ stack?: string[]; } /** * Success response structure with strongly typed data. * Used for providing successful responses to clients. */ interface ApiSuccessResponse<T = any> extends ApiResponse<T> { /** Error always false for success responses */ error: false; /** HTTP status code (usually 200) */ status?: number; } /** * Response structure for batch operations. * Used when multiple operations are performed in a single request. */ interface BatchResponse<T = any> { /** Overall success/failure indicator */ success: boolean; /** Total number of operations */ total: number; /** Number of successful operations */ successful: number; /** Number of failed operations */ failed: number; /** Results of individual operations */ results: Array<{ /** Identifier for this operation */ id: string | number; /** Success/failure indicator for this operation */ success: boolean; /** Response data for this operation */ data?: T; /** Error information if this operation failed */ error?: { message: string; code?: string; }; }>; } /** * Response structure for asynchronous operations. * Used when the operation will complete in the future. */ interface AsyncOperationResponse { /** Always true for async operations */ async: true; /** Job or task ID to check status later */ jobId: string; /** Estimated completion time in seconds (if known) */ estimatedTime?: number; /** URL to check status */ statusUrl: string; } /** * Response structure for streaming operations. * Used when data is returned as a stream rather than all at once. */ interface StreamResponse { /** Stream identifier */ streamId: string; /** Stream type (e.g., 'json', 'binary') */ streamType: string; /** Total size in bytes (if known) */ totalSize?: number; /** Chunk size in bytes */ chunkSize: number; } /** * Sort direction enumeration. */ declare enum SortDirection { /** Ascending sort order */ ASC = "asc", /** Descending sort order */ DESC = "desc" } /** * Pagination parameters for API requests. */ interface PaginationParams { /** Current page number (1-based index) */ page: number; /** Number of records per page */ limit: number; /** Field by which the data is sorted */ sortBy: string; /** Sort order: ascending or descending */ sortOrder: SortDirection; /** Optional search query */ search?: string; } /** * Type that combines pagination parameters with additional data. */ type WithPagination<T = {}> = PaginationParams & T; export { SortDirection, extractFilterParams, extractPaginationParams, extractSortParams, getPaginationParams, parseBooleanParam, parseNumberParam }; export type { ApiErrorResponse, ApiResponse, ApiSuccessResponse, AsyncOperationResponse, BatchResponse, Pagination, PaginationParams, PaginationResponse, StreamResponse, ValidationOptions, ValidationResult, WithPagination };