UNPKG

@snowtop/ent-phonenumber

Version:

snowtop ent phone number datatype

82 lines (81 loc) 2.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PhoneNumberListType = exports.PhoneNumberType = exports.PhoneNumber = void 0; const schema_1 = require("@snowtop/ent/schema"); const libphonenumber_js_1 = require("libphonenumber-js"); class PhoneNumber extends schema_1.BaseField { constructor() { super(...arguments); this.type = { dbType: schema_1.DBType.String }; this._region = "US"; this._format = "E.164"; this._numbers = new Map(); // This calls isPossible() by default and doesn't call isValid() by default // Provides a way to change the default behavior // Also provides a way to validate the number by taking the instance of LibPhoneNumber this._validateForRegion = true; this._validate = false; this.validators = []; } countryCode(region) { this._region = region; return this; } numberFormat(format, formatOptions) { this._format = format; this._formatOptions = formatOptions; return this; } // validate that the number is possible validateForRegion(valid) { this._validateForRegion = valid; return this; } validateNumber(valid) { this._validate = valid; return this; } validate(validator) { this.validators.push(validator); return this; } valid(val) { const phoneNumber = (0, libphonenumber_js_1.parsePhoneNumberFromString)(val, this._region); if (!phoneNumber) { return false; } // TODO isNonGeographic too? // /console.log(phoneNumber.isPossible(), phoneNumber.isNonGeographic()); if (this._validateForRegion && !phoneNumber.isPossible()) { return false; } if (this._validate && !phoneNumber.isValid()) { return false; } for (const validator of this.validators) { if (!validator(phoneNumber)) { return false; } } this._numbers.set(val, phoneNumber); return true; } // PS: need to call valid() before format() format(val) { const number = this._numbers.get(val); if (!number) { throw new Error(`${val} does not seem to be a valid phone number so can't format`); } return number.format(this._format, this._formatOptions); } } exports.PhoneNumber = PhoneNumber; function PhoneNumberType(options) { let result = new PhoneNumber(); return Object.assign(result, options); } exports.PhoneNumberType = PhoneNumberType; function PhoneNumberListType(options) { return new schema_1.ListField(PhoneNumberType(options), options); } exports.PhoneNumberListType = PhoneNumberListType;