UNPKG

@type-ddd/phone

Version:

Library that provides TypeScript type definitions for handling Phone Numbers in Domain-Driven Design contexts. It facilitates the validation and manipulation of Brazilian phone numbers.

73 lines (72 loc) 2.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Phone = void 0; const rich_domain_1 = require("rich-domain"); const mobile_value_object_1 = require("./mobile.value-object"); const home_value_object_1 = require("./home.value-object"); class Phone extends rich_domain_1.ValueObject { /** * * @returns DDD only as number * @example 11 */ static ddd(phone) { const value = this.util.string(phone).removeSpecialChars(); return parseInt(value.slice(0, 2)); } static removeSpecialChars(cell) { const value = this.util.string(cell).removeSpecialChars(); return this.util.string(value).removeSpaces(); } static addMask(cell) { if (this.isMobile(cell)) return mobile_value_object_1.default.addMask(cell); return home_value_object_1.default.addMask(cell); } static isValid(phone) { return this.isValidProps(phone); } static isValidProps(phone) { return this.isHome(phone) || this.isMobile(phone); } static isMobile(phone) { return mobile_value_object_1.default.isValid(phone); } ; static isHome(phone) { return home_value_object_1.default.isValid(phone); } ; /** * * @param value value as string * @returns instance of MobilePhone or HomePhone or throw an error */ static init(value) { const isValid = this.isValidProps(value); if (!isValid) throw new Error(this.MESSAGE); const isMobile = this.isMobile(value); if (isMobile) return mobile_value_object_1.default.init(value); return home_value_object_1.default.init(value); } /** * * @param value Brazilian Mobile or Home phone number * @example (XX) 9XXXX-XXXX or (XX) 3XXX-XXXX * @returns Result of MobilePhone or HomePhone */ static create(value) { const isValid = this.isValidProps(value); if (!isValid) return rich_domain_1.Result.fail(this.MESSAGE); const isMobile = this.isMobile(value); if (isMobile) return mobile_value_object_1.default.create(value); return home_value_object_1.default.create(value); } } exports.Phone = Phone; Phone.MESSAGE = 'Invalid Phone Number'; exports.default = Phone;