aboutsummaryrefslogtreecommitdiff
path: root/src/services/NotificationService.ts
blob: ccaa9135fb631821113f59941a5a2cb94cf96e53 (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
84
85
86
87
88
89
90
91
92
import AsyncStorage from '@react-native-community/async-storage';
import {
  NOTIFICATIONS_ENDPOINT,
  NOTIFICATIONS_COUNT_ENDPOINT,
  NOTIFICATIONS_DATE,
} from '../constants';
import {NotificationType} from '../types';

export const getNotificationsData: () => Promise<NotificationType[]> =
  async () => {
    try {
      const token = await AsyncStorage.getItem('token');
      const response = await fetch(NOTIFICATIONS_ENDPOINT, {
        method: 'GET',
        headers: {
          Authorization: 'Token ' + token,
        },
      });
      if (response.status === 200) {
        const data: any[] = await response.json();
        let typedData: NotificationType[] = [];
        for (const o of data) {
          typedData.push({
            ...o.notification,
            unread: false,
          });
        }
        return typedData;
      }
      return [];
    } catch (error) {
      console.log('Unable to fetch notifications');
      return [];
    }
  };

export const getNotificationsUnreadCount = async () => {
  try {
    const token = await AsyncStorage.getItem('token');
    const response = await fetch(NOTIFICATIONS_COUNT_ENDPOINT, {
      method: 'GET',
      headers: {
        Authorization: 'Token ' + token,
      },
    });
    if (response.status === 200) {
      const data: any = await response.json();
      const typedData: {
        CMT?: number;
        FRD_REQ?: number;
        P_VIEW?: number;
        MOM_TAG?: number;
      } = {};
      if (data.CMT) {
        typedData.CMT = data.CMT;
      }
      if (data.FRD_REQ && data.FRD_REQ > 0) {
        typedData.FRD_REQ = data.FRD_REQ;
      }
      if (data.P_VIEW && data.P_VIEW > 0) {
        typedData.P_VIEW = data.P_VIEW;
      }
      if (data.MOM_TAG && data.MOM_TAG > 0) {
        typedData.MOM_TAG = data.MOM_TAG;
      }
      return typedData;
    }
  } catch (error) {
    console.log('Unable to fetch notifications');
  }
  return undefined;
};

export const setNotificationsReadDate: () => Promise<boolean> = async () => {
  try {
    const token = await AsyncStorage.getItem('token');
    const response = await fetch(NOTIFICATIONS_DATE, {
      method: 'POST',
      headers: {
        Authorization: 'Token ' + token,
      },
    });
    if (response.status === 204) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log('Unable to fetch notifications');
    return false;
  }
};