i18nUtils.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import type { VueI18n } from 'vue-i18n'
  2. import type { CountryCode } from 'libphonenumber-js'
  3. import { parsePhoneNumber } from 'libphonenumber-js'
  4. import type { EnumChoice, EnumChoices } from '~/types/interfaces'
  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((item: EnumChoice) => {
  21. return { value: item.value, label: this.i18n.t(item.label) as string }
  22. })
  23. if (sort) {
  24. // @ts-expect-error enum_ is now an array of EnumChoice
  25. enum_ = ArrayUtils.sortObjectsByProp(enum_, 'label') as EnumChoices
  26. }
  27. return enum_
  28. }
  29. public formatPhoneNumber(
  30. number: string,
  31. defaultCountry?: CountryCode,
  32. ): string {
  33. const parsed = parsePhoneNumber(number, defaultCountry)
  34. return parsed ? parsed.formatNational() : ''
  35. }
  36. }