Skip to content

Commit

Permalink
Fix asset likes repository integration
Browse files Browse the repository at this point in the history
  • Loading branch information
danielailie committed Mar 6, 2023
1 parent 8854e68 commit 5375b1a
Show file tree
Hide file tree
Showing 14 changed files with 105 additions and 171 deletions.
18 changes: 12 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@
"dependencies": {
"@elastic/elasticsearch": "7.12.0",
"@golevelup/nestjs-rabbitmq": "3.4.0",
"@multiversx/sdk-core": "^11.1.3",
"@multiversx/sdk-core": "11.2.0",
"@multiversx/sdk-native-auth-server": "1.0.5",
"@multiversx/sdk-nestjs": "0.3.7",
"@multiversx/sdk-network-providers": "^1.2.1",
"@multiversx/sdk-nestjs": "^0.3.4",
"@nestjs/apollo": "^10.1.7",
"@nestjs/common": "9.1.4",
"@nestjs/config": "2.3.0",
Expand Down
5 changes: 3 additions & 2 deletions src/common/persistence/persistence.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Global, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AccountStatsRepository } from 'src/db/account-stats/account-stats.repository';
import { AssetsLikesRepository } from 'src/db/assets/assets-likes.repository';
import { AuctionEntity } from 'src/db/auctions/auction.entity';
import { AuctionsRepository } from 'src/db/auctions/auctions.repository';
import { TagsRepository } from 'src/db/auctions/tags.repository';
Expand All @@ -27,11 +26,12 @@ import { MxCommunicationModule } from '../services/mx-communication';
import { MarketplaceEventsRepository } from 'src/db/marketplaces/marketplace-events.repository';
import { BlacklistedCollectionsRepository } from 'src/db/blacklistedCollections/blacklisted.repository';
import { ReportCollectionsRepository } from 'src/db/reports';
import { AssetLikeEntity, AssetsLikesRepository } from 'src/db/assets';

@Global()
@Module({
imports: [
TypeOrmModule.forFeature([AssetsLikesRepository]),
TypeOrmModule.forFeature([AssetLikeEntity]),
TypeOrmModule.forFeature([FeaturedCollectionsRepository]),
TypeOrmModule.forFeature([FeaturedNftsRepository]),
TypeOrmModule.forFeature([BlacklistedCollectionsRepository]),
Expand Down Expand Up @@ -59,6 +59,7 @@ import { ReportCollectionsRepository } from 'src/db/reports';
CollectionStatsRepository,
AuctionsRepository,
OffersRepository,
AssetsLikesRepository
],
exports: [PersistenceService, UsdPriceService],
})
Expand Down
9 changes: 3 additions & 6 deletions src/common/services/caching/caching.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from '@multiversx/sdk-nestjs';
import { forwardRef, Global, Module } from '@nestjs/common';
import { CommonModule } from 'src/common.module';
import { LocalRedisCacheService } from './local-redis-cache.service';

@Global()
@Module({
Expand Down Expand Up @@ -35,14 +36,10 @@ import { CommonModule } from 'src/common.module';
}),
),
],
providers: [
// LocalRedisCacheService,
LocalCacheService,
CachingModuleOptions,
],
providers: [LocalRedisCacheService, LocalCacheService, CachingModuleOptions],
exports: [
LocalCacheService,
// LocalRedisCacheService,
LocalRedisCacheService,
ElrondCachingModule.forRoot(
new RedisCacheModuleOptions({
host: process.env.REDIS_URL,
Expand Down
86 changes: 42 additions & 44 deletions src/common/services/caching/local-redis-cache.service.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,45 @@
// import { RedisCacheService } from '@multiversx/sdk-nestjs';
// import { Inject, Injectable, Logger } from '@nestjs/common';
// import { isNil } from '@nestjs/common/utils/shared.utils';
// import Redis from 'ioredis';
// export const REDIS_CLIENT_TOKEN = 'REDIS_CLIENT_TOKEN';
// @Injectable()
// export class LocalRedisCacheService {
// constructor(
// private readonly logger: Logger,
// private readonly redisCacheService: RedisCacheService,
// @Inject('REDIS_CLIENT_TOKEN') private readonly redis: Redis,
// ) {}
import { RedisCacheService } from '@multiversx/sdk-nestjs';
import { Injectable, Logger } from '@nestjs/common';
import { isNil } from '@nestjs/common/utils/shared.utils';
export const REDIS_CLIENT_TOKEN = 'REDIS_CLIENT_TOKEN';
@Injectable()
export class LocalRedisCacheService {
constructor(
private readonly logger: Logger,
private readonly redisCacheService: RedisCacheService,
) {}

// async getOrSetWithDifferentTtl(
// key: string,
// createValueFunc: () => any,
// ): Promise<any> {
// const cachedData = await this.redisCacheService.get(key);
// if (!isNil(cachedData)) {
// return cachedData;
// }
// const value = await this.buildInternalCreateValueFunc(key, createValueFunc);
// await this.redisCacheService.set(key, value, value.ttl);
async getOrSetWithDifferentTtl(
key: string,
createValueFunc: () => any,
): Promise<any> {
const cachedData = await this.redisCacheService.get(key);
if (!isNil(cachedData)) {
return cachedData;
}
const value = await this.buildInternalCreateValueFunc(key, createValueFunc);
await this.redisCacheService.set(key, value, value.ttl);

// return value;
// }
return value;
}

// private async buildInternalCreateValueFunc(
// key: string,
// createValueFunc: () => any,
// ): Promise<any> {
// try {
// let data = createValueFunc();
// if (data instanceof Promise) {
// data = await data;
// }
// return data;
// } catch (err) {
// this.logger.error(`An error occurred while trying to load value.`, {
// path: 'redis-cache.service.createValueFunc',
// exception: err,
// key,
// });
// return null;
// }
// }
// }
private async buildInternalCreateValueFunc(
key: string,
createValueFunc: () => any,
): Promise<any> {
try {
let data = createValueFunc();
if (data instanceof Promise) {
data = await data;
}
return data;
} catch (err) {
this.logger.error(`An error occurred while trying to load value.`, {
path: 'redis-cache.service.createValueFunc',
exception: err,
key,
});
return null;
}
}
}
31 changes: 19 additions & 12 deletions src/db/assets/assets-likes.repository.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MYSQL_ALREADY_EXISTS } from 'src/utils/constants';
import { DeleteResult, EntityRepository, Repository } from 'typeorm';
import { DeleteResult, Repository } from 'typeorm';
import { AssetLikeEntity } from './assets-likes.entity';

@EntityRepository(AssetLikeEntity)
export class AssetsLikesRepository extends Repository<AssetLikeEntity> {
@Injectable()
export class AssetsLikesRepository {

constructor(
@InjectRepository(AssetLikeEntity)
private assetsLikeRepository: Repository<AssetLikeEntity>,
) {}
async getAssetsLiked(
limit: number = 20,
offset: number = 0,
address: string,
): Promise<[AssetLikeEntity[], number]> {
const assetsLiked = await this.createQueryBuilder('assetsLiked')
const assetsLiked = await this.assetsLikeRepository.createQueryBuilder('assetsLiked')
.where({
address: address,
})
Expand All @@ -21,7 +28,7 @@ export class AssetsLikesRepository extends Repository<AssetLikeEntity> {
}

async isAssetLiked(identifier: string, address: string): Promise<boolean> {
const count = await this.count({
const count = await this.assetsLikeRepository.count({
where: {
identifier,
address,
Expand All @@ -32,23 +39,23 @@ export class AssetsLikesRepository extends Repository<AssetLikeEntity> {
}

async getAssetLikesCount(identifier: string): Promise<number> {
return await this.count({
return await this.assetsLikeRepository.count({
where: {
identifier,
},
});
}

async getLikesCountForAddress(address: string): Promise<number> {
return await this.count({
return await this.assetsLikeRepository.count({
where: {
address,
},
});
}

async getBulkAssetLikesCount(identifiers: string[]): Promise<any> {
return await this.createQueryBuilder('al')
return await this.assetsLikeRepository.createQueryBuilder('al')
.select('al.identifier as identifier')
.addSelect('COUNT(al.identifier) as likesCount')
.where(`al.identifier IN(${identifiers.map((value) => `'${value}'`)})`, {
Expand All @@ -59,7 +66,7 @@ export class AssetsLikesRepository extends Repository<AssetLikeEntity> {
}

async getIsLikedAsset(identifiers: string[]): Promise<any> {
return await this.createQueryBuilder('al')
return await this.assetsLikeRepository.createQueryBuilder('al')
.select('CONCAT(al.identifier,"_",al.address) as identifier')
.addSelect('true as liked')
.where(
Expand All @@ -77,7 +84,7 @@ export class AssetsLikesRepository extends Repository<AssetLikeEntity> {

async addLike(assetLikeEntity: AssetLikeEntity): Promise<AssetLikeEntity> {
try {
return await this.save(assetLikeEntity);
return await this.assetsLikeRepository.save(assetLikeEntity);
} catch (err) {
// If like already exists, we ignore the error.
if (err.errno === MYSQL_ALREADY_EXISTS) {
Expand All @@ -88,7 +95,7 @@ export class AssetsLikesRepository extends Repository<AssetLikeEntity> {
}

async removeLike(identifier: string, address: string): Promise<DeleteResult> {
return await this.delete({
return await this.assetsLikeRepository.delete({
identifier,
address,
});
Expand All @@ -98,7 +105,7 @@ export class AssetsLikesRepository extends Repository<AssetLikeEntity> {
offset?: number,
limit?: number,
): Promise<AssetLikeEntity[]> {
return await this.createQueryBuilder('al')
return await this.assetsLikeRepository.createQueryBuilder('al')
.select('count(*) as cnt, al.identifier')
.groupBy('al.identifier')
.orderBy('cnt', 'DESC')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import {
} from 'nest-winston';
import * as winston from 'winston';
import * as Transport from 'winston-transport';
import { MxApiService, RedisCacheService } from 'src/common';
import { MxApiService } from 'src/common';
import { AccountStatsEntity } from 'src/db/account-stats/account-stats';
import { RedisCacheServiceMock } from 'src/common/services/caching/redis-cache.service.mock';
import { MxApiServiceMock } from 'src/common/services/mx-communication/mx-api.service.mock';
import { AccountStatsRepository } from 'src/db/account-stats/account-stats.repository';
import { AccountStatsRepositoryMock } from 'src/db/account-stats/account-stats.repository-mock';
Expand Down Expand Up @@ -39,11 +38,6 @@ describe.skip('AccountsStatsService', () => {
useClass: AccountStatsRepositoryMock,
};

const RedisCacheServiceProvider = {
provide: RedisCacheService,
useClass: RedisCacheServiceMock,
};

const logTransports: Transport[] = [
new winston.transports.Console({
format: winston.format.combine(
Expand All @@ -59,7 +53,6 @@ describe.skip('AccountsStatsService', () => {
AccountStatsRepositoryProvider,
AccountsStatsService,
MarketplaceServiceProvider,
RedisCacheServiceProvider,
AccountsStatsCachingServiceProvider,
],
imports: [
Expand Down
7 changes: 3 additions & 4 deletions src/modules/assets/asset-by-identifier.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,23 @@ import { Asset, NftTypeEnum } from './models';
import { generateCacheKeyFromParams } from 'src/utils/generate-cache-key';
import { TimeConstants } from 'src/utils/time-utils';
import { Constants, RedisCacheService } from '@multiversx/sdk-nestjs';
import { LocalRedisCacheService } from 'src/common/services/caching/local-redis-cache.service';

@Injectable()
export class AssetByIdentifierService {
constructor(
private apiService: MxApiService,
private readonly logger: Logger,
// private localRedisCacheService: LocalRedisCacheService,
private localRedisCacheService: RedisCacheService,
private localRedisCacheService: LocalRedisCacheService, // private localRedisCacheService: RedisCacheService,
) {}

public async getAsset(identifier: string): Promise<Asset> {
try {
const cacheKey = this.getAssetsCacheKey(identifier);
const getAsset = () => this.getMappedAssetByIdentifier(identifier);
const asset = await this.localRedisCacheService.getOrSet(
const asset = await this.localRedisCacheService.getOrSetWithDifferentTtl(
cacheKey,
getAsset,
Constants.oneDay(),
);
return asset?.value ? asset?.value : null;
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import {
} from 'nest-winston';
import * as winston from 'winston';
import * as Transport from 'winston-transport';
import { MxApiService, RedisCacheService } from 'src/common';
import { RedisCacheServiceMock } from 'src/common/services/caching/redis-cache.service.mock';
import { MxApiService } from 'src/common';
import { CollectionStatsRepository } from 'src/db/collection-stats/collection-stats.repository';
import { CollectionStatsRepositoryMock } from 'src/db/collection-stats/collection-stats.repository-mock';
import { CollectionStatsEntity } from 'src/db/collection-stats/collection-stats';
Expand All @@ -25,11 +24,6 @@ describe.skip('CollectionsStatsService', () => {
useClass: CollectionStatsRepositoryMock,
};

const RedisCacheServiceProvider = {
provide: RedisCacheService,
useClass: RedisCacheServiceMock,
};

const logTransports: Transport[] = [
new winston.transports.Console({
format: winston.format.combine(
Expand All @@ -44,7 +38,6 @@ describe.skip('CollectionsStatsService', () => {
MxApiServiceProvider,
CollectionStatsRepositoryProvider,
CollectionsStatsService,
RedisCacheServiceProvider,
],
imports: [
WinstonModule.forRoot({
Expand Down
Loading

0 comments on commit 5375b1a

Please sign in to comment.