Thêm tính năng bình luận ở mỗi điểm của chặng

This commit is contained in:
2026-06-16 08:27:54 +07:00
parent c5530f36df
commit 5464d90948
15 changed files with 1427 additions and 97 deletions
+8
View File
@@ -1 +1,9 @@
import 'reflect-metadata';
import { OnGatewayConnection } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
export declare class CommentGateway implements OnGatewayConnection {
server: Server;
handleConnection(client: Socket): void;
handleJoinTour(client: Socket, tourId: string): void;
notifyNewComment(tourId: string, data: any): void;
}
+97 -4
View File
@@ -45,6 +45,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommentGateway = void 0;
const dotenv = __importStar(require("dotenv"));
const path = __importStar(require("path"));
const envPath = path.resolve(process.cwd(), '..', '.env');
@@ -52,6 +53,8 @@ dotenv.config({ path: envPath });
require("reflect-metadata");
const core_1 = require("@nestjs/core");
const common_1 = require("@nestjs/common");
const websockets_1 = require("@nestjs/websockets");
const socket_io_1 = require("socket.io");
const prisma_service_1 = require("../prisma/prisma.service");
const bcrypt = __importStar(require("bcrypt"));
const admin_guard_1 = require("./auth/admin.guard");
@@ -358,7 +361,10 @@ let TourController = class TourController {
legs: {
orderBy: { sequence: 'asc' },
include: {
locations: { orderBy: { plannedStart: 'asc' } }
locations: {
orderBy: { plannedStart: 'asc' },
include: { _count: { select: { comments: true } } }
}
}
}
}
@@ -379,7 +385,10 @@ let TourController = class TourController {
legs: {
orderBy: { sequence: 'asc' },
include: {
locations: { orderBy: { plannedStart: 'asc' } },
locations: {
orderBy: { plannedStart: 'asc' },
include: { _count: { select: { comments: true } } }
},
},
},
},
@@ -1014,6 +1023,90 @@ UserController = __decorate([
(0, common_1.Controller)('users'),
__metadata("design:paramtypes", [prisma_service_1.PrismaService])
], UserController);
let CommentGateway = class CommentGateway {
handleConnection(client) {
console.log(`[WS] Client connected: ${client.id}`);
}
handleJoinTour(client, tourId) {
client.join(`tour_${tourId}`);
console.log(`[WS] Client ${client.id} joined room: tour_${tourId}`);
}
notifyNewComment(tourId, data) {
this.server.to(`tour_${tourId}`).emit('commentAdded', data);
}
};
exports.CommentGateway = CommentGateway;
__decorate([
(0, websockets_1.WebSocketServer)(),
__metadata("design:type", socket_io_1.Server)
], CommentGateway.prototype, "server", void 0);
__decorate([
(0, websockets_1.SubscribeMessage)('joinTour'),
__metadata("design:type", Function),
__metadata("design:paramtypes", [socket_io_1.Socket, String]),
__metadata("design:returntype", void 0)
], CommentGateway.prototype, "handleJoinTour", null);
exports.CommentGateway = CommentGateway = __decorate([
(0, websockets_1.WebSocketGateway)({ cors: { origin: '*' } })
], CommentGateway);
let CommentController = class CommentController {
constructor(prisma, commentGateway) {
this.prisma = prisma;
this.commentGateway = commentGateway;
}
async getComments(locationId) {
return this.prisma.comment.findMany({
where: { locationId },
include: {
user: { select: { name: true } }
},
orderBy: { createdAt: 'asc' }
});
}
async addComment(locationId, body, req) {
const comment = await this.prisma.comment.create({
data: {
content: body.content,
locationId,
userId: req.user.id
},
include: { user: { select: { name: true } } }
});
const location = await this.prisma.location.findUnique({
where: { id: locationId },
include: { leg: { select: { tourId: true } } }
});
if (location?.leg?.tourId) {
this.commentGateway.notifyNewComment(location.leg.tourId, {
...comment,
locationId
});
}
return comment;
}
};
__decorate([
(0, common_1.Get)(':locationId/comments'),
__param(0, (0, common_1.Param)('locationId', common_1.ParseUUIDPipe)),
__metadata("design:type", Function),
__metadata("design:paramtypes", [String]),
__metadata("design:returntype", Promise)
], CommentController.prototype, "getComments", null);
__decorate([
(0, common_1.Post)(':locationId/comments'),
__param(0, (0, common_1.Param)('locationId', common_1.ParseUUIDPipe)),
__param(1, (0, common_1.Body)()),
__param(2, (0, common_1.Req)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [String, Object, Object]),
__metadata("design:returntype", Promise)
], CommentController.prototype, "addComment", null);
CommentController = __decorate([
(0, common_1.Controller)('locations'),
(0, common_1.UseGuards)(jwt_auth_guard_1.JwtAuthGuard),
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
CommentGateway])
], CommentController);
let AppModule = class AppModule {
};
AppModule = __decorate([
@@ -1024,8 +1117,8 @@ AppModule = __decorate([
signOptions: { expiresIn: '1d' },
}),
],
controllers: [AppController, AuthController, TourController, UserController, RoutingController, LegController, LocationController],
providers: [prisma_service_1.PrismaService, jwt_strategy_1.JwtStrategy, rbac_middleware_1.TourRoleGuard, jwt_auth_guard_1.JwtAuthGuard, admin_guard_1.AdminGuard],
controllers: [AppController, AuthController, TourController, UserController, RoutingController, LegController, LocationController, CommentController],
providers: [prisma_service_1.PrismaService, jwt_strategy_1.JwtStrategy, rbac_middleware_1.TourRoleGuard, jwt_auth_guard_1.JwtAuthGuard, admin_guard_1.AdminGuard, CommentGateway],
exports: [prisma_service_1.PrismaService]
})
], AppModule);
+1 -1
View File
File diff suppressed because one or more lines are too long
+8 -3
View File
@@ -5,15 +5,17 @@
"start:dev": "nest start --watch",
"db:generate": "dotenv -e ../.env -- prisma generate --schema=prisma/schema.prisma",
"db:migrate": "dotenv -e ../.env -- prisma migrate dev --schema=prisma/schema.prisma",
"db:seed": "node --loader ts-node/esm seed.ts"
"db:seed": "dotenv -e ../.env -- tsx seed.ts"
},
"devDependencies": {
"@nestjs/cli": "^11.0.23",
"@types/bcrypt": "^5.0.2",
"@types/node": "^20.14.10",
"@types/pg": "^8.11.6",
"dotenv-cli": "^7.4.2",
"prisma": "^5.16.2",
"ts-node": "^10.9.2",
"tsx": "^4.19.2",
"typescript": "^5.5.3"
},
"dependencies": {
@@ -22,14 +24,17 @@
"@nestjs/jwt": "^11.0.2",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.1.27",
"@prisma/client": "^5.16.2",
"@nestjs/platform-socket.io": "^11.1.27",
"@nestjs/websockets": "^11.1.27",
"@prisma/adapter-pg": "^5.16.2",
"@prisma/client": "^5.16.2",
"bcrypt": "^6.0.0",
"dotenv": "^17.4.2",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pg": "^8.12.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2"
"rxjs": "^7.8.2",
"socket.io": "^4.8.3"
}
}
@@ -0,0 +1,16 @@
-- CreateTable
CREATE TABLE "Comment" (
"id" TEXT NOT NULL,
"content" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"locationId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "Comment_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "Comment" ADD CONSTRAINT "Comment_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "Location"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Comment" ADD CONSTRAINT "Comment_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+13
View File
@@ -73,6 +73,8 @@ model User {
receivedJoinRequests JoinRequest[] @relation("JoinRequester")
uploadedPhotos Photo[]
paidExpenses Expense[] @relation("ExpensePaidBy")
comments Comment[]
}
model Tour {
@@ -157,6 +159,7 @@ model Location {
leg Leg @relation(fields: [legId], references: [id], onDelete: Cascade)
expenses Expense[]
photos Photo[]
comments Comment[]
}
model Expense {
@@ -188,3 +191,13 @@ model Photo {
location Location? @relation(fields: [locationId], references: [id], onDelete: SetNull)
uploader User @relation(fields: [uploaderId], references: [id])
}
model Comment {
id String @id @default(uuid())
content String
createdAt DateTime @default(now())
locationId String
location Location @relation(fields: [locationId], references: [id], onDelete: Cascade)
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
+25 -2
View File
@@ -1,8 +1,12 @@
import { PrismaClient } from '@prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { Pool } from 'pg';
import 'dotenv/config';
import * as bcrypt from 'bcrypt';
import * as dotenv from 'dotenv';
import * as path from 'path';
import bcrypt from 'bcrypt';
const envPath = path.resolve(process.cwd(), '..', '.env');
dotenv.config({ path: envPath });
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
@@ -90,6 +94,25 @@ async function main() {
},
});
console.log('--- Đang tạo bình luận mẫu... ---');
const dinhDocLap = await prisma.location.findFirst({ where: { name: 'Dinh Độc Lập' } });
if (dinhDocLap) {
await prisma.comment.createMany({
data: [
{
content: 'Chỗ này rất đẹp, giàu giá trị lịch sử!',
locationId: dinhDocLap.id,
userId: owner.id,
},
{
content: 'Nên đi vào buổi sáng cho mát mẻ mọi người nhé.',
locationId: dinhDocLap.id,
userId: photoMember.id,
}
],
});
}
console.log('--- Seed dữ liệu hoàn tất! ---');
console.log(`Email đăng nhập Owner: ${owner.email}`);
console.log(`Email đăng nhập Photo Only: ${photoMember.email}`);
+85 -6
View File
@@ -7,7 +7,9 @@ dotenv.config({ path: envPath });
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get, Post, Body, Param, Patch, Delete, ParseUUIDPipe, NotFoundException, BadRequestException, UnauthorizedException, UseGuards, Req, Query, ForbiddenException } from '@nestjs/common';
import { Module, Controller, Get, Post, Body, Param, Patch, Delete, ParseUUIDPipe, NotFoundException, BadRequestException, UnauthorizedException, UseGuards, Req, Query, ForbiddenException, Injectable } from '@nestjs/common';
import { WebSocketGateway, WebSocketServer, SubscribeMessage, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { PrismaService } from '../prisma/prisma.service';
import * as bcrypt from 'bcrypt';
import { AdminGuard } from './auth/admin.guard';
@@ -360,7 +362,10 @@ class TourController {
legs: {
orderBy: { sequence: 'asc' },
include: {
locations: { orderBy: { plannedStart: 'asc' } }
locations: {
orderBy: { plannedStart: 'asc' },
include: { _count: { select: { comments: true } } }
}
}
}
}
@@ -384,7 +389,10 @@ class TourController {
legs: {
orderBy: { sequence: 'asc' },
include: {
locations: { orderBy: { plannedStart: 'asc' } },
locations: {
orderBy: { plannedStart: 'asc' },
include: { _count: { select: { comments: true } } }
},
},
},
},
@@ -871,15 +879,86 @@ class UserController {
}
}
@WebSocketGateway({ cors: { origin: '*' } })
export class CommentGateway implements OnGatewayConnection {
@WebSocketServer() server: Server;
handleConnection(client: Socket) {
console.log(`[WS] Client connected: ${client.id}`);
}
@SubscribeMessage('joinTour')
handleJoinTour(client: Socket, tourId: string) {
client.join(`tour_${tourId}`);
console.log(`[WS] Client ${client.id} joined room: tour_${tourId}`);
}
notifyNewComment(tourId: string, data: any) {
// Gửi thông báo tới tất cả client trong phòng của Tour này
this.server.to(`tour_${tourId}`).emit('commentAdded', data);
}
}
@Controller('locations')
@UseGuards(JwtAuthGuard)
class CommentController {
constructor(
private prisma: PrismaService,
private commentGateway: CommentGateway
) {}
@Get(':locationId/comments')
async getComments(@Param('locationId', ParseUUIDPipe) locationId: string) {
return this.prisma.comment.findMany({
where: { locationId },
include: {
user: { select: { name: true } }
},
orderBy: { createdAt: 'asc' }
});
}
@Post(':locationId/comments')
async addComment(
@Param('locationId', ParseUUIDPipe) locationId: string,
@Body() body: { content: string },
@Req() req: any
) {
const comment = await this.prisma.comment.create({
data: {
content: body.content,
locationId,
userId: req.user.id
},
include: { user: { select: { name: true } } }
});
// Tìm tourId để gửi thông báo vào đúng phòng
const location = await this.prisma.location.findUnique({
where: { id: locationId },
include: { leg: { select: { tourId: true } } }
});
if (location?.leg?.tourId) {
this.commentGateway.notifyNewComment(location.leg.tourId, {
...comment,
locationId // Gửi kèm locationId để UI biết điểm nào cần tăng số lượng
});
}
return comment;
}
}
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET || 'super-secret',
signOptions: { expiresIn: '1d' },
}),
}) as any,
],
controllers: [AppController, AuthController, TourController, UserController, RoutingController, LegController, LocationController],
providers: [PrismaService, JwtStrategy, TourRoleGuard, JwtAuthGuard, AdminGuard],
controllers: [AppController, AuthController, TourController, UserController, RoutingController, LegController, LocationController, CommentController],
providers: [PrismaService, JwtStrategy, TourRoleGuard, JwtAuthGuard, AdminGuard, CommentGateway],
exports: [PrismaService]
})
class AppModule {}