All files / src/Handle TypeOrmHandleProvider.ts

87.75% Statements 43/49
53.33% Branches 8/15
100% Functions 11/11
85.71% Lines 36/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 12640x                 40x 40x 40x 40x       40x 2x   40x       1x 1x       5x   7x   4x 4x 4x 4x   4x   4x 5x 4x                           4x   4x 4x 4x                         4x                             4x         5x         1x 1x 1x 1x         1x   1x       1x     1x 1x                    
import {
  Cardano,
  HandleProvider,
  HandleResolution,
  Point,
  ProviderError,
  ProviderFailure,
  ResolveHandlesArgs
} from '@cardano-sdk/core';
import { HandleEntity, HandleMetadataEntity, NftMetadataEntity } from '@cardano-sdk/projection-typeorm';
import { In } from 'typeorm';
import { InMemoryCache } from '../InMemoryCache';
import { TypeormProvider, TypeormProviderDependencies } from '../util/TypeormProvider';
 
export type TypeOrmHandleProviderDependencies = TypeormProviderDependencies;
 
export const emptyStringHandleResolutionRequestError = () =>
  new ProviderError(ProviderFailure.BadRequest, undefined, "Empty string handle can't be resolved");
 
export class TypeOrmHandleProvider extends TypeormProvider implements HandleProvider {
  inMemoryCache: InMemoryCache;
 
  constructor(deps: TypeOrmHandleProviderDependencies) {
    super('TypeOrmHandleProvider', deps);
    this.inMemoryCache = new InMemoryCache(0);
  }
 
  async resolveHandles(args: ResolveHandlesArgs) {
    const { handles } = args;
 
    for (const handle of handles) if (!handle) throw emptyStringHandleResolutionRequestError();
 
    return this.withDataSource(async (dataSource) => {
      const queryRunner = dataSource.createQueryRunner();
      const query = 'SELECT hash, slot FROM block WHERE slot = (SELECT MAX(slot) FROM block)';
      const resolvedAt = <Point>(await queryRunner.query(query))[0];
 
      await queryRunner.release();
 
      const mapEntity = async (entity: HandleEntity | undefined): Promise<HandleResolution | null> => {
        if (!entity) return null;
        Iif (!entity.cardanoAddress) {
          this.logger.warn(`${entity.handle} has no associated address, which could be the result of a double mint.`);
          return null;
        }
 
        const {
          cardanoAddress,
          handle,
          hasDatum,
          parentHandle,
          policyId,
          defaultForPaymentCredential,
          defaultForStakeCredential,
          asset
        } = entity;
 
        const nftMetadataRepo = dataSource.getRepository(NftMetadataEntity);
        const handleMetadataRepo = dataSource.getRepository(HandleMetadataEntity);
        const [nftMetadataEntity, handleMetadataEntity] = await Promise.all([
          nftMetadataRepo.findOne({
            order: { id: 'DESC' },
            select: { id: true, image: true },
            where: { userTokenAssetId: asset!.id }
          }),
          handleMetadataRepo.findOne({
            order: { id: 'DESC' },
            select: { backgroundImage: true, id: true, profilePicImage: true },
            where: { handle }
          })
        ]);
 
        return {
          backgroundImage: handleMetadataEntity?.backgroundImage || undefined,
          cardanoAddress,
          defaultForPaymentCredential: defaultForPaymentCredential || undefined,
          defaultForStakeCredential: defaultForStakeCredential || undefined,
          handle: handle!,
          hasDatum: !!hasDatum,
          image: nftMetadataEntity?.image,
          parentHandle: parentHandle?.handle,
          policyId: policyId!,
          profilePic: handleMetadataEntity?.profilePicImage || undefined,
          resolvedAt
        };
      };
 
      const entities = await dataSource.getRepository(HandleEntity).find({
        loadRelationIds: { disableMixedMap: true },
        where: { handle: In(handles) }
      });
 
      return Promise.all(handles.map((handle) => mapEntity(entities.find((entity) => entity.handle === handle))));
    });
  }
 
  async getPolicyIds(): Promise<Cardano.PolicyId[]> {
    return this.withDataSource(async (dataSource) => {
      const columnName = 'policy_id';
      const fetchPolicyIdsFromDB = async () => {
        const distinctPolicyIds = await dataSource
          .getRepository(HandleEntity)
          .createQueryBuilder('handle')
          .select(`DISTINCT ${columnName}`, columnName)
          .getRawMany();
        const policyIds = distinctPolicyIds.map((row) => row[columnName]);
 
        Iif (policyIds.length === 0) {
          throw new Error('Value from the database is 0');
        }
 
        return policyIds;
      };
 
      try {
        return this.inMemoryCache.get('policyIds', fetchPolicyIdsFromDB);
      } catch (error) {
        Iif (error instanceof Error && error.message === 'Value from the database is 0') {
          return [];
        }
        throw error;
      }
    });
  }
}