i18nUtils.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. enum_ = ArrayUtils.sortObjectsByProp(enum_, 'label') as EnumChoices
  25. }
  26. return enum_
  27. }
  28. public formatPhoneNumber(
  29. number: string,
  30. defaultCountry?: CountryCode,
  31. ): string {
  32. const parsed = parsePhoneNumber(number, defaultCountry)
  33. return parsed ? parsed.formatNational() : ''
  34. }
  35. }