File size: 2,424 Bytes
1773f9a
464b662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1773f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464b662
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
import { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';
import { WhatsappService } from '../whatsapp/whatsapp.service';

@Controller('get/groups')
export class GroupController {
  constructor(private readonly whatsappService: WhatsappService) {}

  @Get('/')
  async getGroups(@Res() res: any) {
    try {
      const sock = this.whatsappService.getSocket();

      const groups = await sock.groupFetchAllParticipating();

      const formattedGroups = Object.values(groups).map((g) => ({
        name: g.subject,
        jid: g.id,
        participants: g.participants.length,
      }));

      // Kirim respons sukses
      return res.status(HttpStatus.OK).json({
        status: 'Success',
        data: formattedGroups,
      });
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Unknown error';
      console.error('Gagal mengambil data grup:', message);

      const cachedGroups = this.whatsappService.getAllGroupsCache();

      if (cachedGroups.length > 0) {
        return res.status(HttpStatus.OK).json({
          status: 'Success (Cached)',
          data: cachedGroups,
        });
      }

      return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
        status: 'Error',
        message: 'Gagal mengambil grup dan cache kosong: ' + message,
      });
    }
  }

  @Get('id')
  async getGroupId(
    @Query('name') name: string,
    @Query('jid') jid: string,
    @Res() res: any,
  ) {
    try {
      if (jid) {
        return res.status(HttpStatus.OK).json({ status: 'Success', data: { jid } });
      }

      if (!name) {
        return res.status(HttpStatus.BAD_REQUEST).json({ status: 'Error', message: 'Query `name` atau `jid` diperlukan.' });
      }

      const cached = this.whatsappService.getAllGroupsCache();
      const matches = cached.filter((g) => g.name && g.name.toLowerCase().includes(name.toLowerCase()));

      if (matches.length > 0) {
        return res.status(HttpStatus.OK).json({ status: 'Success', data: matches });
      }

      return res.status(HttpStatus.NOT_FOUND).json({ status: 'NotFound', message: 'Tidak ditemukan grup yang cocok.' });
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Unknown error';
      console.error('Gagal mencari ID grup:', message);
      return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ status: 'Error', message });
    }
  }
}