index.ts57 lines, 1.3 KB
| 1 | import { ApiResponse, ServiceError } from "../types"; |
| 2 | |
| 3 | export function createApiResponse<T>( |
| 4 | success: boolean, |
| 5 | data?: T, |
| 6 | message?: string, |
| 7 | error?: string |
| 8 | ): ApiResponse<T> { |
| 9 | return { |
| 10 | success, |
| 11 | data, |
| 12 | message, |
| 13 | error, |
| 14 | }; |
| 15 | } |
| 16 | |
| 17 | export function createSuccessResponse<T>( |
| 18 | data: T, |
| 19 | message?: string |
| 20 | ): ApiResponse<T> { |
| 21 | return createApiResponse(true, data, message); |
| 22 | } |
| 23 | |
| 24 | export function createErrorResponse(error: string): ApiResponse { |
| 25 | return createApiResponse(false, undefined, undefined, error); |
| 26 | } |
| 27 | |
| 28 | export function createServiceError( |
| 29 | message: string, |
| 30 | statusCode: number = 500, |
| 31 | code?: string, |
| 32 | details?: any |
| 33 | ): ServiceError { |
| 34 | return new ServiceError(message, statusCode, code, details); |
| 35 | } |
| 36 | |
| 37 | // Sanitize user input data to prevent XSS and other attacks |
| 38 | export function sanitizeInput(input: string): string { |
| 39 | return input |
| 40 | .replace(/[<>]/g, "") // remove < and > characters |
| 41 | .trim(); // trim whitespace |
| 42 | } |
| 43 | |
| 44 | export function isValidUUID(uuid: string): boolean { |
| 45 | const regex = |
| 46 | /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/; |
| 47 | return regex.test(uuid); |
| 48 | } |
| 49 | |
| 50 | export function parseEnvInt( |
| 51 | value: string | undefined, |
| 52 | defaultValue: number |
| 53 | ): number { |
| 54 | if (!value) return defaultValue; |
| 55 | const parsedValue = parseInt(value, 10); |
| 56 | return isNaN(parsedValue) ? defaultValue : parsedValue; |
| 57 | } |