utils.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { AnyMessage, AnyMetadataClass, DecodedMetadataObject } from './types'
  2. import countries from 'i18n-iso-countries'
  3. import langs from 'iso-639-1'
  4. import subdivisions from 'iso-3166-2'
  5. export function isSet<T>(v: T | null | undefined): v is T {
  6. return v !== null && v !== undefined
  7. }
  8. export function isEmptyObject<T>(object: T): boolean {
  9. return Object.keys(object).length === 0
  10. }
  11. export function integrateMeta<
  12. T,
  13. Props extends readonly (keyof T & keyof M & string)[],
  14. M extends { [K in Props[number]]?: T[K] | null }
  15. >(object: T, meta: M, props: Props): void {
  16. props.forEach((prop) => {
  17. const metaPropVal = meta[prop] as T[Props[number]] | null | undefined
  18. if (isSet(metaPropVal)) {
  19. object[prop] = metaPropVal
  20. }
  21. })
  22. }
  23. export function encodeDecode<T>(metaClass: AnyMetadataClass<T>, value: T): DecodedMetadataObject<T> {
  24. const encoded = metaClass.encode(value).finish()
  25. return metaToObject(metaClass, metaClass.decode(encoded))
  26. }
  27. export function metaToObject<T>(metaClass: AnyMetadataClass<T>, value: AnyMessage<T>): DecodedMetadataObject<T> {
  28. // Default conversion options - use Strings for "Long" values and ignore unset "repeated" fields
  29. return metaClass.toObject(value, { arrays: false, longs: String }) as DecodedMetadataObject<T>
  30. }
  31. // Checks if the provided code is valid according to ISO 3166-1 alpha-2 standard
  32. export function isValidCountryCode(code: string): boolean {
  33. return countries.getAlpha2Codes()[code] !== undefined
  34. }
  35. // Checks if the provided code is valid according to ISO 639-1 standard
  36. export function isValidLanguageCode(code: string): boolean {
  37. return langs.validate(code)
  38. }
  39. // According to ISO 3166-2 standard
  40. export function isValidSubdivisionCode(code: string): boolean {
  41. return !!subdivisions.subdivision(code)
  42. }