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.

343 lines (338 loc) 12.7 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 { ApiResponse as ApiResponse$1, ApiErrorResponse as ApiErrorResponse$1 } from '@catbee/utils/response'; /** * Standard HTTP response wrapper for successful responses. * Implements the `ApiResponse<T>` interface and sets default values. * * @typeParam T - The shape of the data returned in the response. */ declare class SuccessResponse<T> implements ApiResponse$1<T> { /** Message describing the result of the operation. */ message: string; /** Whether the response is an error. Always false in success responses. */ error: boolean; /** The payload returned from the API. */ data: T | null; /** Timestamp when the response was generated, in ISO format. */ timestamp: string; /** Unique identifier for this response, useful for request tracing. */ requestId: string; /** * Constructs a new success response. * * @param {string} message - Optional message to override the default. * @param {T} [data] - Optional data payload. */ constructor(message: string, data?: T); } /** * Wrapper for error responses that extends the native `Error` object. * Implements `ApiResponse` but omits the `data` field (which should not be present in errors). */ declare class ErrorResponse extends Error implements Omit<ApiResponse$1<never>, 'data'> { /** HTTP status code associated with the error (e.g., 404, 500). */ status: number; /** Indicates that this is an error. Always true. */ error: boolean; /** Timestamp when the error occurred, in ISO format. */ timestamp: string; /** Unique identifier for this error instance. */ requestId: string; /** * Constructs a new error response. * * @param {string} message - The error message to display or log. * @param {number} [status=500] - Optional HTTP status code (defaults to 500). */ constructor(message: string, status?: number); } /** * Response with paginated data extending the standard success response. * Useful for APIs that return large collections of data. * * @typeParam T - The shape of each item in the paginated collection. */ declare class PaginatedResponse<T> extends SuccessResponse<T[]> { /** Total number of items across all pages */ total: number; /** Current page number (1-based) */ page: number; /** Number of items per page */ pageSize: number; /** Total number of pages */ totalPages: number; /** Whether there's a next page available */ hasNext: boolean; /** Whether there's a previous page available */ hasPrevious: boolean; /** * Constructs a new paginated response. * * @param {T[]} items - The current page of items. * @param {Object} pagination - Pagination information. * @param {number} pagination.total - Total number of items across all pages. * @param {number} pagination.page - Current page number (1-based). * @param {number} pagination.pageSize - Number of items per page. * @param {string} [message="Success"] - Optional custom message. */ constructor(items: T[], pagination: { total: number; page: number; pageSize: number; }, message?: string); } /** * Specialized response for operations that don't return data (HTTP 204). */ declare class NoContentResponse extends SuccessResponse<null> { /** * Constructs a new no-content response. * * @param {string} [message="Operation completed successfully"] - Optional custom message. */ constructor(message?: string); } /** * Specialized response for redirects. */ declare class RedirectResponse { /** The URL to redirect to */ redirectUrl: string; /** HTTP status code for the redirect (301, 302, 303, 307, 308) */ statusCode: number; /** Whether the response is a redirect */ isRedirect: boolean; /** Unique identifier for this response */ requestId: string; /** * Constructs a new redirect response. * * @param {string} url - The URL to redirect to. * @param {number} [statusCode=302] - HTTP status code for the redirect. */ constructor(url: string, statusCode?: number); } /** * Creates a standard success response. * * @typeParam T - The shape of the data returned in the response. * @param {T} data - The data to include in the response. * @param {string} [message="Success"] - Optional custom message. * @returns {SuccessResponse<T>} A properly formatted success response. */ declare function createSuccessResponse<T>(data: T, message?: string): SuccessResponse<T>; /** * Creates a standard error response. * * @param {string} message - The error message. * @param {number} [statusCode=500] - HTTP status code for the error. * @returns {ErrorResponse} A properly formatted error response. */ declare function createErrorResponse(message: string, statusCode?: number): ErrorResponse; /** * Creates a final error response with request information. * * @param req - The original request object. * @param status - The HTTP status code. * @param message - The error message. * @param error - The original error object (optional). * @param options - Additional options for the response (optional). * @returns A properly formatted final error response. */ declare function createFinalErrorResponse(req: Request, status: number, message: string, error?: any, options?: { includeDetails?: boolean; }): ApiErrorResponse$1; /** * Creates a paginated response from array data. * * @typeParam T - The shape of each item in the collection. * @param {T[]} allItems - The complete array of items to paginate. * @param {number} page - The requested page (1-based). * @param {number} pageSize - The number of items per page. * @param {string} [message="Success"] - Optional custom message. * @returns {PaginatedResponse<T>} A properly formatted paginated response. */ declare function createPaginatedResponse<T>(allItems: T[], page: number, pageSize: number, message?: string): PaginatedResponse<T>; /** * Adapter to convert API responses to Express.js response format. * * @param {any} res - Express response object. * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance. */ declare function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void; /** * 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 { ErrorResponse, NoContentResponse, PaginatedResponse, RedirectResponse, SortDirection, SuccessResponse, createErrorResponse, createFinalErrorResponse, createPaginatedResponse, createSuccessResponse, sendResponse }; export type { ApiErrorResponse, ApiResponse, ApiSuccessResponse, AsyncOperationResponse, BatchResponse, Pagination, PaginationParams, PaginationResponse, StreamResponse, WithPagination };