i18nUtils.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import {VueI18n} from "vue-i18n";
  2. import {EnumChoice, EnumChoices} from "~/types/interfaces";
  3. import {CountryCode, parsePhoneNumber} from "libphonenumber-js";
  4. import ArrayUtils from "~/services/utils/arrayUtils";
  5. export default class I18nUtils {
  6. private i18n!: VueI18n
  7. public constructor(i18n: VueI18n) {
  8. this.i18n = i18n
  9. }
  10. /**
  11. * Return the given enum with its labels translated
  12. *
  13. * If sort is true, the enum is also sorted by its newly translated labels
  14. *
  15. * @param enum_
  16. * @param sort
  17. */
  18. public translateEnum(enum_: EnumChoices, sort: boolean = true): EnumChoices {
  19. enum_ = enum_.map(
  20. (item: EnumChoice) => {
  21. return {value: item.value, label: this.i18n.t(item.label) as string}
  22. }
  23. )
  24. if (sort) {
  25. enum_ = ArrayUtils.sortObjectsByProp(enum_, 'label') as EnumChoices
  26. }
  27. return enum_
  28. }
  29. public formatPhoneNumber (number: string, defaultCountry?: CountryCode): string {
  30. const parsed = parsePhoneNumber(number, defaultCountry)
  31. return parsed ? parsed.formatNational() : ''
  32. }
  33. }