-
Notifications
You must be signed in to change notification settings - Fork 0
/
track.service.ts
60 lines (53 loc) · 1.88 KB
/
track.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
// // Логика работы с БД, получить, вернуть, не зависит от запроса
import { CreateTrackDto } from './dto/create-track.dto';
@Injectable()
export class TrackService {
constructor(
@InjectModel(Track.name) private trackModel: Model<TrackDocument>,
@InjectModel(Comment.name) private commentModel: Model<CommentDocument>,
private fileService: FileService,
) {}
async create(dto: CreateTrackDto, picture, audio): Promise<Track> {
const audioPath = this.fileService.createFile(Filetype.AUDIO, audio);
const picturePath = this.fileService.createFile(FileType.IMAGE, picture);
const track = await this.trackModel.create({
...dto,
listens: 0,
audio: audioPath,
picture: picturePath,
});
return track;
}
async getAll(count = 10, offset = 0): Promise<Track[]> {
const tracks = await this.trackModel
.find()
.skip(Number(offset))
.limit(Number(count));
return tracks;
}
async getOne(id: ObjectId): Promise<Track> {
const track = await this.trackModel.findById(id).populate('comments');
return track;
}
async delete(id: ObjectId): Promise<ObjectId> {
const track = await this.trackModel.findByIdAndDelete(id);
return track._id;
}
async addComment(dto: CreateCommentDto): Promise<Comment> {
const track = await this.trackModel.findById(dto.trackId);
const comment = await this.trackModel.create({ ...dto });
track.comments.push(comment._id);
await track.save();
return comment;
}
async listen(id: ObjectId) {
const track = await this.trackModel.findById(id);
track.listens += 1;
track.save();
}
async search(query: string): Promise<Track[]> {
const tracks = await this.trackModel.find({
name: {$regex: new RegExp(query, 'i')}
});
return tracks;
}