summaryrefslogtreecommitdiff
path: root/server/providers/services/chat_room.service.ts
blob: 148ff19e4352faa871bb0c14c053b33a8c08110c (plain)
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
74
75
76
77
78
79
80
81
82
83
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ChatRoom } from 'server/entities/chat_room.entity';
import { User } from 'server/entities/user.entity';
import { ChatRoomConnection } from 'server/entities/chat_room_connection.entity';

@Injectable()
export class ChatRoomService {
  constructor(
    @InjectRepository(ChatRoom)
    private chatRoomRepository: Repository<ChatRoom>,
    @InjectRepository(ChatRoomConnection)
    private connectedUsersRepository: Repository<ChatRoomConnection>,
  ) {}

  create(chatRoom: ChatRoom) {
    return this.chatRoomRepository.save(chatRoom);
  }

  all() {
    return this.chatRoomRepository.find();
  }

  nearOrUserOwns({ lat, lng, userId }: { lat: number; lng: number; userId: number }) {
    // SQL injection maybe?
    return this.chatRoomRepository.query(
      `SELECT * FROM chat_room WHERE calculate_distance(latitude, longitude, ${lat}, ${lng}, 'M') < 5 OR "userId" = ${userId}`,
    );
  }

  findById(id: string, relations: string[] = []) {
    return this.chatRoomRepository.findOne(id, { relations });
  }

  async connectedUsers(chatRoom: ChatRoom) {
    return this.connectedUsersRepository
      .find({
        where: { chatRoom },
        relations: ['user'],
      })
      .then((x) =>
        x.map((x) => {
          return {
            id: x.user.id,
            userName: `${x.user.firstName} ${x.user.lastName}`,
          };
        }),
      );
  }

  connectUser = async function (chatRoom: ChatRoom, user: User) {
    const connectedUser = await this.connectedUsersRepository.findOne({
      where: { chatRoom, user },
    });
    if (connectedUser) {
      return connectedUser;
    }
    const chatRoomConnection = new ChatRoomConnection();
    chatRoomConnection.chatRoom = chatRoom;
    chatRoomConnection.user = user;
    await this.connectedUsersRepository.save(chatRoomConnection);
    return this.connectedUsers(chatRoom);
  };

  disconnectUser = async function (chatRoom: ChatRoom, user: User) {
    const connectedUser = await this.connectedUsersRepository.findOne({
      where: { chatRoom, user },
    });
    if (connectedUser) {
      return this.connectedUsersRepository.remove(connectedUser);
    }
    return false;
  };

  save(chatRoom: ChatRoom) {
    return this.chatRoomRepository.save(chatRoom);
  }

  remove(chatRoom: ChatRoom) {
    return this.chatRoomRepository.remove(chatRoom);
  }
}