common.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { DatabaseManager } from '@joystream/hydra-common'
  2. import { BaseModel } from '@joystream/warthog'
  3. import { WorkingGroup } from '@joystream/types/augment/all'
  4. import { AnyMetadataClass, DecodedMetadataObject } from '@joystream/metadata-protobuf/types'
  5. import { metaToObject } from '@joystream/metadata-protobuf/utils'
  6. import { Bytes } from '@polkadot/types'
  7. type EntityClass<T extends BaseModel> = {
  8. new (): T
  9. name: string
  10. }
  11. type RelationsArr<T extends BaseModel> = Exclude<
  12. keyof T & string,
  13. { [K in keyof T]: T[K] extends BaseModel | undefined ? '' : T[K] extends BaseModel[] | undefined ? '' : K }[keyof T]
  14. >[]
  15. export async function getById<T extends BaseModel>(
  16. store: DatabaseManager,
  17. entityClass: EntityClass<T>,
  18. id: string,
  19. relations?: RelationsArr<T>
  20. ): Promise<T> {
  21. const result = await store.get(entityClass, { where: { id }, relations })
  22. if (!result) {
  23. throw new Error(`Expected ${entityClass.name} not found by ID: ${id}`)
  24. }
  25. return result
  26. }
  27. export type WorkingGroupModuleName = 'storageWorkingGroup' | 'contentDirectoryWorkingGroup'
  28. export function getWorkingGroupModuleName(group: WorkingGroup): WorkingGroupModuleName {
  29. if (group.isContent) {
  30. return 'contentDirectoryWorkingGroup'
  31. } else if (group.isStorage) {
  32. return 'storageWorkingGroup'
  33. }
  34. throw new Error(`Unsupported working group encountered: ${group.type}`)
  35. }
  36. export function deserializeMetadata<T>(
  37. metadataType: AnyMetadataClass<T>,
  38. metadataBytes: Bytes
  39. ): DecodedMetadataObject<T> | null {
  40. try {
  41. return metaToObject(metadataType, metadataType.decode(metadataBytes.toU8a(true)))
  42. } catch (e) {
  43. console.error(`Cannot deserialize ${metadataType.name}! Provided bytes: (${metadataBytes.toHex()})`)
  44. return null
  45. }
  46. }
  47. export function bytesToString(b: Bytes): string {
  48. return (
  49. Buffer.from(b.toU8a(true))
  50. .toString()
  51. // eslint-disable-next-line no-control-regex
  52. .replace(/\u0000/g, '')
  53. )
  54. }