Skip to content

Commit

Permalink
🐛 fix: 조회수 차트 데이터 계산 문제 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
kms0219kms committed Sep 26, 2024
1 parent a29089c commit cdb97ce
Show file tree
Hide file tree
Showing 7 changed files with 513 additions and 413 deletions.
33 changes: 16 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,31 @@
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix"
},
"dependencies": {
"@fastify/csrf-protection": "^6.4.1",
"@fastify/static": "^7.0.4",
"@fastify/static": "^7.0.0",
"@nestjs/axios": "^3.0.3",
"@nestjs/cache-manager": "^2.2.2",
"@nestjs/common": "^10.4.1",
"@nestjs/common": "^10.4.4",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.4.1",
"@nestjs/core": "^10.4.4",
"@nestjs/jwt": "^10.2.0",
"@nestjs/platform-fastify": "^10.4.1",
"@nestjs/swagger": "^7.4.0",
"axios": "^1.7.4",
"@nestjs/platform-fastify": "^10.4.4",
"@nestjs/swagger": "^7.4.2",
"axios": "^1.7.7",
"cache-manager": "^5.7.6",
"cache-manager-redis-yet": "^5.1.4",
"fastify": "^4.28.1",
"mongoose": "^8.5.3",
"nestjs-redox": "^1.2.1",
"cache-manager-redis-yet": "^5.1.5",
"fastify": "^5.0.0",
"mongoose": "^8.6.3",
"nestjs-redox": "^1.2.2",
"redoc": "^2.1.5",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@nestjs/cli": "^10.4.4",
"@nestjs/cli": "^10.4.5",
"@nestjs/schematics": "^10.1.4",
"@types/node": "^22.4.2",
"@typescript-eslint/eslint-plugin": "^8.2.0",
"@typescript-eslint/parser": "^8.2.0",
"@types/node": "^22.7.3",
"@typescript-eslint/eslint-plugin": "^8.7.0",
"@typescript-eslint/parser": "^8.7.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
Expand All @@ -50,7 +49,7 @@
"ts-loader": "^9.5.1",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.5.4"
"typescript": "^5.6.2"
},
"jest": {
"moduleFileExtensions": [
Expand All @@ -69,5 +68,5 @@
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"packageManager": "pnpm@9.7.1+sha512.faf344af2d6ca65c4c5c8c2224ea77a81a5e8859cbc4e06b1511ddce2f0151512431dd19e6aff31f2c6a8f5f2aced9bd2273e1fed7dd4de1868984059d2c4247"
"packageManager": "pnpm@9.11.0+sha512.0a203ffaed5a3f63242cd064c8fb5892366c103e328079318f78062f24ea8c9d50bc6a47aa3567cabefd824d170e78fa2745ed1f16b132e16436146b7688f19b"
}
788 changes: 423 additions & 365 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

20 changes: 10 additions & 10 deletions src/charts/charts.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,31 @@ export class ChartsService {

async getChart(type: ChartType = 'realtime'): Promise<chartDto> {
try {
const musicData = await this.trackService.getTracksMany(100);
const chartData = SerializeJson.serialize<IStatistics[]>(
await this.statisticsModel.find(),
await this.statisticsModel.find().sort({
[`${type}.views`]: -1,
}),
);
const updatedAt = SerializeJson.serialize<IStatisticsUpdatedAt>(
await this.statisticsUpdatedAtModel.findOne(),
);

const musicData = await this.trackService.getTracksByIds(
// get only first 100 tracks
chartData.map((data) => data.id).slice(0, 100),
);

return {
chart: musicData
.map((music) => {
const chart = chartData.find((data) => data.id === music.id);

return {
...music,
rank: chart?.[type] || { current: 0, increase: 'NEW' },
rank: chart?.[type] || { views: 0, rank: 'NEW' },
};
})
.sort((a, b) => {
if (a.rank.increase === 'NEW') return 1;
else if (b.rank.increase === 'NEW') return -1;
else if (a.rank.current > b.rank.current) return 1;
else if (a.rank.current < b.rank.current) return -1;
else return 0;
}),
.sort((a, b) => b.rank.views - a.rank.views),
updatedAt: new Date(updatedAt[type]).toISOString(),
};
} catch (e) {
Expand Down
4 changes: 2 additions & 2 deletions src/charts/dto/chart.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ class ChartData extends musicDetailDto {
* 현재 조회수 값
* @example 1
*/
current: number;
views: number;

/**
* 조회수 증감량
* @example NEW
*/
increase: number | string;
rank: number | 'NEW';
};
}

Expand Down
36 changes: 26 additions & 10 deletions src/common/repository/schemas/statistics.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export interface IStatistics {
}

export type IStatisticData = {
current: number;
increase: number;
views: number;
rank: number | 'NEW';
};

export const StatisticsSchema = new mongoose.Schema<IStatistics>({
Expand All @@ -20,35 +20,51 @@ export const StatisticsSchema = new mongoose.Schema<IStatistics>({
required: true,
},
realtime: {
current: {
views: {
type: Number,
required: true,
default: 0,
},
increase: Number || null,
rank: {
type: Number || String,
required: true,
default: 'NEW',
},
},
daily: {
current: {
views: {
type: Number,
required: true,
default: 0,
},
increase: Number || null,
rank: {
type: Number || String,
required: true,
default: 'NEW',
},
},
total: {
current: {
views: {
type: Number,
required: true,
default: 0,
},
increase: Number || null,
rank: {
type: Number || String,
required: true,
default: 'NEW',
},
},
weekly: {
current: {
views: {
type: Number,
required: true,
default: 0,
},
increase: Number || null,
rank: {
type: Number || String,
required: true,
default: 'NEW',
},
},
});
12 changes: 3 additions & 9 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import {
NestFastifyApplication,
} from '@nestjs/platform-fastify';

import fastifyCsrf from '@fastify/csrf-protection';

import { AppModule } from './app.module';
import { version } from '../package.json';

Expand All @@ -24,8 +22,8 @@ async function bootstrap() {
//#region -- OpenAPI Spec 설정
if (process.env.ENABLE_SWAGGER != '0') {
const config = new DocumentBuilder()
.setTitle('WAKTAPLAY Music API')
.setDescription('WAKTAPLAY Music 서비스를 위한 백엔드 RestAPI 입니다.')
.setTitle('WAKTAPLAY API')
.setDescription('WAKTAPLAY 서비스를 위한 백엔드 RestAPI 입니다.')
.setVersion(version)
.addBearerAuth()
.build();
Expand All @@ -37,7 +35,7 @@ async function bootstrap() {
}
//#endregion

//#region -- CORS + CSRF 설정
//#region -- CORS 설정
if (process.env.GLOBAL_CORS == '1') {
app.enableCors({
origin: '*',
Expand All @@ -49,10 +47,6 @@ async function bootstrap() {
// credentials: true,
});
}

await app.register(fastifyCsrf, {
sessionPlugin: '@fastify/secure-session',
});
//#endregion

app.useGlobalFilters(new GlobalExceptionFilter());
Expand Down
33 changes: 33 additions & 0 deletions src/songs/songs.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,37 @@ export class SongsService {
};
});
}

async getTracksByIds(ids: string[]): Promise<musicDetailDto[]> {
const musicResponse = await this.musicModel
.find()
.where('id')
.in(ids)
.select('-_id -__v -artist -videos.reaction -videos.etc');

const heartsResponse = await this.heartsModel.find();

return musicResponse.map((music) => {
const hearts = heartsResponse.filter((heart) => heart.music === music.id);

// artTrack이 0이나 빈 문자열로 날라오는 경우 대비
music.videos.artTrack =
music.videos.artTrack === '0' || music.videos.artTrack === ''
? null
: music.videos.artTrack;

// 장르, 키워드가 빈 문자열로 날라오는 경우 대비
music.genres = music.genres.filter((g) => g !== '');
music.keywords = music.keywords.filter((k) => k !== '');

return {
...SerializeJson.serialize<IMusic>(music),

hearts: hearts.length,

// TODO: 유저 정보를 받아서 해당 유저가 좋아요를 눌렀는지 확인하는 로직 추가
isHearted: null,
};
});
}
}

0 comments on commit cdb97ce

Please sign in to comment.