i18nUtils.ts 1.2 KB

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