UNPKG

@type-ddd/zip-code

Version:

This package provides TypeScript type definitions for handling Brazilian Zip Code in Domain-Driven Design contexts

84 lines (83 loc) 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ZipCode = void 0; const rich_domain_1 = require("rich-domain"); const regexHash = /^[0-9]{5}-[0-9]{3}$|^[0-9]{8}$/; class ZipCode extends rich_domain_1.ValueObject { constructor(prop) { super(prop); } /** * @returns value as string. always only numbers * @example 75520140 */ value() { return this.props; } /** * @description add hyphen and dot to cpf value. * @example before "75520140" * @example after "75520-140" */ static addMask(zipCode) { if (typeof zipCode !== 'string') return ''; if (zipCode.includes('-')) return zipCode.slice(0, 9); return zipCode.slice(0, 5) + '-' + zipCode.slice(5, 8); } /** * @description remove hyphen and dot from cpf value. * @example before "75520-140" * @example after "75520140" */ static removeSpecialChars(zipCode) { return this.util.string(zipCode).removeSpecialChars(); } /** * @description add special chars to numbers * @returns zip code as string following pattern xxxxx-xxx */ toPattern() { return ZipCode.addMask(this.props); } /** * * @param value PostalCode as string * @returns true if value match with pattern and false if do not. */ static isValid(value) { return this.isValidProps(value); } /** * * @param value PostalCode as string * @returns true if value match with pattern and false if do not. */ static isValidProps(value) { return this.validator.string(value).match(ZipCode.REGEX); } /** * * @param value value as string * @returns instance of ZipCode or throw an error */ static init(value) { const isValidValue = ZipCode.isValidProps(value); if (!isValidValue) throw new Error(ZipCode.MESSAGE); const numbers = ZipCode.removeSpecialChars(value); return new ZipCode(numbers); } static create(value) { if (!ZipCode.isValidProps(value)) { return rich_domain_1.Result.fail(ZipCode.MESSAGE); } const numbers = ZipCode.removeSpecialChars(value); return rich_domain_1.Result.Ok(new ZipCode(numbers)); } } exports.ZipCode = ZipCode; ZipCode.REGEX = regexHash; ZipCode.MESSAGE = 'Invalid zip code'; exports.default = ZipCode;