UNPKG

trade360-nodejs-sdk

Version:
64 lines 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IdTransformerUtil = void 0; const zod_1 = require("zod"); const id_transformation_error_1 = require("../entities/errors/id-transformation.error"); /** * Utility class for ID transformations across entities. * Provides reusable transformation logic for converting various ID types to strings * with strict validation to ensure only numeric integer values are accepted. */ class IdTransformerUtil { /** * Transforms various ID types to string format with strict validation. * Only accepts: * - Positive integers (number type) * - Numeric strings containing only digits * * Rejects: * - Decimal numbers (e.g., 123.45) * - Non-numeric strings (e.g., 'invalid', 'abc123') * - Negative numbers * - NaN, Infinity, null, undefined * * @param value - The ID value to transform (number, string, etc.) * @param fieldName - The name of the field being transformed (for error reporting) * @returns The ID as a string * @throws IdTransformationError if the value is invalid */ static transformId(value, fieldName = 'Id') { if (value === null || value === undefined) { throw new id_transformation_error_1.IdTransformationError(fieldName, value, 'Field is required but received null or undefined'); } if (typeof value === 'number') { try { const validatedNumber = this.numericSchema.parse(value); return validatedNumber.toString(); } catch (error) { throw new id_transformation_error_1.IdTransformationError(fieldName, value, `Invalid number: ${error instanceof zod_1.z.ZodError ? error.errors[0]?.message : 'must be a positive integer'}`); } } if (typeof value === 'string') { try { const validatedString = this.numericStringSchema.parse(value.trim()); return validatedString; } catch (error) { throw new id_transformation_error_1.IdTransformationError(fieldName, value, `Invalid string ID: ${error instanceof zod_1.z.ZodError ? error.errors[0]?.message : 'must contain only digits'}`); } } throw new id_transformation_error_1.IdTransformationError(fieldName, value, `Unsupported type: ${typeof value}`); } } exports.IdTransformerUtil = IdTransformerUtil; IdTransformerUtil.numericStringSchema = zod_1.z .string() .regex(/^\d+$/, 'ID must contain only digits') .refine((val) => val.length > 0, 'ID cannot be empty'); IdTransformerUtil.numericSchema = zod_1.z .number() .int('ID must be an integer') .finite('ID must be a finite number') .nonnegative('ID must be non-negative'); //# sourceMappingURL=id-transformer-util.js.map