|
1 | 1 | import { Injectable } from '@nestjs/common';
|
2 | 2 | import { InjectRepository } from '@nestjs/typeorm';
|
3 |
| -import { Repository } from 'typeorm'; |
| 3 | +import { Connection, getRepository, Repository } from 'typeorm'; |
| 4 | +import { Board } from '../board/entities/board.entity'; |
4 | 5 | import { LikeBoard } from '../board/entities/likeBoard.entity';
|
| 6 | +import { User } from '../user/entities/user.entity'; |
5 | 7 |
|
6 | 8 | @Injectable()
|
7 | 9 | export class LikeBoardService {
|
8 | 10 | constructor(
|
9 | 11 | @InjectRepository(LikeBoard)
|
10 | 12 | private readonly likeBoardRepository: Repository<LikeBoard>,
|
| 13 | + |
| 14 | + private readonly connection: Connection, |
11 | 15 | ) {}
|
12 | 16 |
|
13 | 17 | async find(userId) {
|
14 |
| - const arts = await this.likeBoardRepository.find({ userId: userId }); |
15 |
| - return arts.map((ele) => ele.board); |
| 18 | + const queryRunner = this.connection.createQueryRunner(); |
| 19 | + await queryRunner.connect(); |
| 20 | + await queryRunner.startTransaction(); |
| 21 | + try { |
| 22 | + const boards = await queryRunner.manager.find(LikeBoard, { |
| 23 | + where: { userId }, |
| 24 | + relations: ['board'], |
| 25 | + }); |
| 26 | + return boards.map((ele) => ele.board); |
| 27 | + } catch (error) { |
| 28 | + await queryRunner.rollbackTransaction(); |
| 29 | + throw error + 'find board!!!'; |
| 30 | + } finally { |
| 31 | + await queryRunner.manager.release(); |
| 32 | + } |
16 | 33 | }
|
17 | 34 |
|
18 | 35 | async like(boardId, userId) {
|
| 36 | + const queryRunner = this.connection.createQueryRunner(); |
| 37 | + await queryRunner.connect(); |
| 38 | + await queryRunner.startTransaction(); |
19 | 39 | try {
|
20 |
| - const prevLike = await this.likeBoardRepository.findOne({ |
21 |
| - userId: userId, |
22 |
| - }); |
23 |
| - if (prevLike.board !== boardId) { |
24 |
| - await this.likeBoardRepository.save({ |
| 40 | + const board = await queryRunner.manager.findOne(Board, { id: boardId }); |
| 41 | + const prevLike = await queryRunner.manager.findOne(LikeBoard, { |
| 42 | + where: { |
25 | 43 | userId: userId,
|
26 | 44 | board: boardId,
|
| 45 | + }, |
| 46 | + }); |
| 47 | + if (!prevLike) { |
| 48 | + await queryRunner.manager.save(LikeBoard, { |
| 49 | + userId: userId, |
| 50 | + board: board, |
27 | 51 | });
|
| 52 | + await queryRunner.commitTransaction(); |
| 53 | + return true; |
28 | 54 | } else {
|
29 |
| - await this.likeBoardRepository.delete({ userId: userId }); |
| 55 | + await queryRunner.manager.delete(LikeBoard, { board: boardId }); |
| 56 | + await queryRunner.commitTransaction(); |
| 57 | + return false; |
30 | 58 | }
|
31 |
| - return true; |
32 | 59 | } catch (error) {
|
| 60 | + await queryRunner.rollbackTransaction(); |
33 | 61 | throw error + 'like board!!!';
|
| 62 | + } finally { |
| 63 | + await queryRunner.manager.release(); |
34 | 64 | }
|
35 | 65 | }
|
36 | 66 |
|
|
0 commit comments