This repository has been archived by the owner on Nov 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstudent-comment.service.ts
73 lines (63 loc) · 1.93 KB
/
student-comment.service.ts
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
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { StudentEntity } from '../student.entity';
import { UserEntity } from '../../user/user.entity';
import { BadDataException, IdNotFoundException } from '../student.exception';
import { CommentEntity } from './student-comment.entity';
import { GetCommentResponseDto } from './student-comment.dto';
@Injectable()
export class CommentService {
constructor(
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>,
@InjectRepository(StudentEntity)
private studentRepository: Repository<StudentEntity>,
@InjectRepository(CommentEntity)
private commentRepository: Repository<CommentEntity>,
) {}
async findByStudentPaginated(
id: number,
page: number = 1,
): Promise<GetCommentResponseDto> {
const student = await this.studentRepository.findOne({ where: { id } });
const [comments, count] = await this.commentRepository.findAndCount({
where: { student },
select: ['id', 'content', 'datetime'],
take: 20,
skip: (page - 1) * 20,
order: { id: 'DESC' },
});
return {
data: comments,
count,
next: page * 20 >= count ? null : page + 1,
};
}
async create(
{ username },
id: number,
data: { content: string },
): Promise<any> {
Object.keys(data).forEach((key) => {
if (!['content'].includes(key)) {
throw new BadDataException();
}
});
if (!data.content) {
throw new BadDataException();
}
const user = await this.userRepository.findOne({ where: { username } });
const student = await this.studentRepository.findOne({
where: { id, user },
});
if (!student) {
throw new IdNotFoundException();
}
await this.commentRepository.save({
content: data.content,
student,
});
return { success: true };
}
}