Skip to content

Commit

Permalink
refactor: ♻️ coalition model 개편, 관련 함수 수정
Browse files Browse the repository at this point in the history
- imageUrl => imgUrl 로 변경, 사용하지 않는 field 들 deprecate
- page/common/ 으로 이동
- 수정 중 scoreService 의 winCountPerCoalition 이 slow query 임을 발견하고 수정

- #378
  • Loading branch information
jpham005 committed Oct 30, 2023
1 parent 65c1921 commit f8ae027
Show file tree
Hide file tree
Showing 12 changed files with 101 additions and 67 deletions.
4 changes: 3 additions & 1 deletion app/src/api/coalition/coalition.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { InjectModel } from '@nestjs/mongoose';
import type { Aggregate, Model } from 'mongoose';
import { API_CONFIG } from 'src/config/api';
import { CDN_CONFIG } from 'src/config/cdn';
import type { Coalition } from '../../page/common/models/coalition.model';
import { coalition } from './db/coalition.database.schema';
import type { Coalition } from './models/coalition.model';

@Injectable()
export class CoalitionService {
Expand All @@ -26,7 +26,9 @@ export class CoalitionService {
return {
...dao,
coverUrl: this.coverUrlById(dao.id),
// todo: deprecated at v0.9.0
imageUrl: this.imageUrlById(dao.id),
imgUrl: this.imageUrlById(dao.id),
color: dao.color ?? '#161616',
};
}
Expand Down
28 changes: 0 additions & 28 deletions app/src/api/coalition/models/coalition.model.ts

This file was deleted.

7 changes: 7 additions & 0 deletions app/src/api/score/score.cache.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { ScoreService } from './score.service';
export const SCORE_RANKING = 'scoreRanking';
export const TOTAL_SCORES_BY_COALITION = 'totalScoresByCoalition';
export const SCORE_RECORDS = 'scoreRecords';
export const WIN_COUNT_PER_COALITION = 'winCountPerCoalition';

export type ScoreRankingSupportedDateTemplate = Extract<
RankingSupportedDateTemplate,
Expand Down Expand Up @@ -63,4 +64,10 @@ export class ScoreCacheService {
> {
return await this.cacheUtilService.getWithoutDate(SCORE_RECORDS);
}

async getWinCountPerCoalition(): Promise<
ReturnType<ScoreService['winCountPerCoalition']> | undefined
> {
return await this.cacheUtilService.getWithoutDate(WIN_COUNT_PER_COALITION);
}
}
52 changes: 32 additions & 20 deletions app/src/api/score/score.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { InjectModel } from '@nestjs/mongoose';
import type { FilterQuery, Model } from 'mongoose';
import { RUNTIME_CONFIG } from 'src/config/runtime';
import { addRank } from 'src/database/mongoose/database.mongoose.aggregation';
import { DateWrapper } from 'src/dateWrapper/dateWrapper';
import type {
IntPerCoalition,
ScoreRecordPerCoalition,
Expand Down Expand Up @@ -75,9 +76,11 @@ export class ScoreService {
const targetCoalitionIds =
args?.targetCoalitionIds ?? this.coalitionService.getSeoulCoalitionIds();

const aggregate = this.scoreModel.aggregate<IntPerCoalition>();
const aggregate = this.scoreModel.aggregate<
Omit<IntPerCoalition, 'coalition'> & { coalition: coalition }
>();

return await aggregate
const scoresPerCoalitionDao = await aggregate
.match({
coalitionsUserId: { $ne: null },
coalitionId: { $in: targetCoalitionIds },
Expand All @@ -93,6 +96,11 @@ export class ScoreService {
coalition: { $first: '$coalitions' },
value: 1,
});

return scoresPerCoalitionDao.map(({ value, coalition }) => ({
coalition: this.coalitionService.daoToDto(coalition),
value,
}));
}

async scoreRecordsPerCoalition(args?: {
Expand All @@ -102,10 +110,11 @@ export class ScoreService {
const targetCoalitionIds =
args?.targetCoalitionIds ?? this.coalitionService.getSeoulCoalitionIds();

const aggregate =
this.coalitionService.aggregate<ScoreRecordPerCoalition>();
const aggregate = this.coalitionService.aggregate<
Omit<ScoreRecordPerCoalition, 'coalition'> & { coalition: coalition }
>();

return await aggregate
const scoreRecordsPerCoalitionDao = await aggregate
.match({
id: { $in: targetCoalitionIds },
})
Expand Down Expand Up @@ -160,6 +169,11 @@ export class ScoreService {
},
},
});

return scoreRecordsPerCoalitionDao.map(({ coalition, records }) => ({
coalition: this.coalitionService.daoToDto(coalition),
records,
}));
}

async tigCountPerCoalition(args?: {
Expand Down Expand Up @@ -202,20 +216,17 @@ export class ScoreService {
);
}

async winCountPerCoalition(args?: {
targetCoalitionIds?: readonly number[];
filter?: FilterQuery<score>;
}): Promise<IntPerCoalition[]> {
const targetCoalitionIds =
args?.targetCoalitionIds ?? this.coalitionService.getSeoulCoalitionIds();
async winCountPerCoalition(): Promise<IntPerCoalition[]> {
const endDate = new DateWrapper().startOfMonth().toDate();

const aggregate = this.scoreModel.aggregate<IntPerCoalition>();
const aggregate = this.scoreModel.aggregate<
Omit<IntPerCoalition, 'coalition'> & { coalition: coalition }
>();

return await aggregate
const winCountPerCoalitionDao = await aggregate
.match({
...args?.filter,
createdAt: { $lt: endDate },
coalitionsUserId: { $ne: null },
coalitionId: { $in: targetCoalitionIds },
})
.group({
_id: {
Expand All @@ -242,16 +253,17 @@ export class ScoreService {
_id: '$winCoalition._id.coalitionId',
value: { $count: {} },
})
.sort({ _id: 1 })
.append(lookupCoalition('_id', 'id'))
.project({
_id: 0,
coalition: { $first: '$coalitions' },
value: 1,
})
.then((winCountPerCoalition) => {
return winCountPerCoalition.sort(
(a, b) => a.coalition.id - b.coalition.id,
);
});

return winCountPerCoalitionDao.map(({ coalition, value }) => ({
coalition: this.coalitionService.daoToDto(coalition),
value,
}));
}
}
2 changes: 1 addition & 1 deletion app/src/common/userFullProfile.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Coalition } from 'src/api/coalition/models/coalition.model';
import type { Coalition } from 'src/page/common/models/coalition.model';
import type { cursus_user } from 'src/api/cursusUser/db/cursusUser.database.schema';
import type { title } from 'src/api/title/db/title.database.schema';
import type { titles_user } from 'src/api/titlesUser/db/titlesUser.database.schema';
Expand Down
12 changes: 12 additions & 0 deletions app/src/lambda/lambda.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
SCORE_RANKING,
SCORE_RECORDS,
TOTAL_SCORES_BY_COALITION,
WIN_COUNT_PER_COALITION,
} from 'src/api/score/score.cache.service';
import { ScoreService } from 'src/api/score/score.service';
import { CacheUtilRankingService } from 'src/cache/cache.util.ranking.service';
Expand Down Expand Up @@ -177,6 +178,7 @@ export class LambdaService {

await this.updateTotalScoresPerCoalition(updatedAt);
await this.updateScoreRecords(updatedAt);
await this.updateWinCountPerCoalition(updatedAt);

const currMonthExp = await this.experienceUserService.increamentRanking(
expIncreamentDateFilter(currMonth),
Expand Down Expand Up @@ -301,4 +303,14 @@ export class LambdaService {
updatedAt,
);
}

private async updateWinCountPerCoalition(updatedAt: Date): Promise<void> {
const winCountPerCoalition = await this.scoreService.winCountPerCoalition();

await this.cacheUtilService.setWithDate(
WIN_COUNT_PER_COALITION,
winCountPerCoalition,
updatedAt,
);
}
}
34 changes: 34 additions & 0 deletions app/src/page/common/models/coalition.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Field, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class Coalition {
@Field()
id: number;

@Field()
name: string;

@Field({ deprecationReason: 'deprecated at v0.9.0' })
slug: string;

@Field({ deprecationReason: 'deprecated at v0.9.0, imgUrl 을 사용하세요.' })
imageUrl: string;

@Field()
imgUrl: string;

@Field()
coverUrl: string;

@Field()
color: string;

@Field({ deprecationReason: 'deprecated at v0.9.0' })
score: number;

@Field({
description: '코알리숑 마스터의 user id 입니다.',
deprecationReason: 'deprecated at v0.9.0',
})
userId: number;
}
14 changes: 4 additions & 10 deletions app/src/page/home/coalition/home.coalition.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { scoreDateRangeFilter } from 'src/api/score/db/score.database.aggregate'
import { ScoreCacheService } from 'src/api/score/score.cache.service';
import { ScoreService } from 'src/api/score/score.service';
import { CacheOnReturn } from 'src/cache/decrators/onReturn/cache.decorator.onReturn.symbol';
import { assertExist } from 'src/common/assertExist';
import type { IntRecord } from 'src/common/models/common.valueRecord.model';
import { DateRangeService } from 'src/dateRange/dateRange.service';
import { DateRange, DateTemplate } from 'src/dateRange/dtos/dateRange.dto';
Expand Down Expand Up @@ -86,17 +87,10 @@ export class HomeCoalitionService {
return this.dateRangeService.toDateRanged(tigCountPerCoalition, dateRange);
}

@CacheOnReturn()
async winCountPerCoalition(): Promise<IntPerCoalition[]> {
const currmonth = new DateWrapper().startOfMonth();

const dateRange: DateRange = {
...this.dateRangeService.dateRangeFromTemplate(DateTemplate.TOTAL),
end: currmonth.toDate(),
};
const cached = await this.scoreCacheService.getWinCountPerCoalition();
assertExist(cached);

return await this.scoreService.winCountPerCoalition({
filter: scoreDateRangeFilter(dateRange),
});
return cached;
}
}
2 changes: 1 addition & 1 deletion app/src/page/home/coalition/models/home.coalition.model.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Field, ObjectType } from '@nestjs/graphql';
import { Coalition } from 'src/api/coalition/models/coalition.model';
import { Coalition } from 'src/page/common/models/coalition.model';
import { IntRecord } from 'src/common/models/common.valueRecord.model';
import { ArrayDateRanged } from 'src/dateRange/models/dateRange.model';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { InternalServerErrorException } from '@nestjs/common';
import type { Coalition } from 'src/api/coalition/models/coalition.model';
import type { Coalition } from 'src/page/common/models/coalition.model';

export type PokemonType = {
readonly name: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Field, Float, ObjectType } from '@nestjs/graphql';
import { Coalition } from 'src/api/coalition/models/coalition.model';
import { Coalition } from 'src/page/common/models/coalition.model';

@ObjectType()
export class UserTitle {
Expand Down
9 changes: 5 additions & 4 deletions app/src/schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,15 @@ type ProjectPreview {
type Coalition {
id: Int!
name: String!
slug: String!
imageUrl: String!
slug: String! @deprecated(reason: "deprecated at v0.9.0")
imageUrl: String! @deprecated(reason: "deprecated at v0.9.0, imgUrl 을 사용하세요.")
imgUrl: String!
coverUrl: String!
color: String!
score: Int!
score: Int! @deprecated(reason: "deprecated at v0.9.0")

"""코알리숑 마스터의 user id 입니다."""
userId: Int!
userId: Int! @deprecated(reason: "deprecated at v0.9.0")
}

type UserTitle {
Expand Down

0 comments on commit f8ae027

Please sign in to comment.