aboutsummaryrefslogtreecommitdiff
path: root/src/services/BlockUserService.ts
blob: 12ea0184db90aceac3b5cef15c0faa9b41a93a54 (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
//Abstracted common block user api calls out here

import {Alert} from 'react-native';
import {BLOCK_USER_ENDPOINT} from '../constants';
import {ERROR_SOMETHING_WENT_WRONG_REFRESH} from '../constants/strings';

export const loadBlockedUsers = async (userId: string, token: string) => {
  try {
    const response = await fetch(BLOCK_USER_ENDPOINT + `?user_id=${userId}`, {
      method: 'GET',
      headers: {
        Authorization: 'Token ' + token,
      },
    });
    if (response.status === 200) {
      const body = await response.json();
      return body;
    } else {
      throw new Error(await response.json());
    }
  } catch (error) {
    console.log(error);
  }
};

export const blockOrUnblockUser = async (
  blocker: string,
  blocked: string,
  token: string,
  isBlocked: boolean,
) => {
  try {
    const endpoint = BLOCK_USER_ENDPOINT + (isBlocked ? `${blocker}/` : '');

    const response = await fetch(endpoint, {
      method: isBlocked ? 'DELETE' : 'POST',
      headers: {
        Authorization: 'Token ' + token,
      },
      body: JSON.stringify({
        blocked,
      }),
    });
    if (Math.floor(response.status / 100) === 2) {
      return true;
    } else {
      console.log(await response.json());
      Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH);
      return false;
    }
  } catch (error) {
    console.log(error);
    Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH);
    return false;
  }
};

export const isUserBlocked = async (
  blocker: string,
  blocked: string,
  token: string,
) => {
  try {
    const ext = `${blocked}/?blocker=${blocker}`;

    const response = await fetch(BLOCK_USER_ENDPOINT + ext, {
      method: 'GET',
      headers: {
        Authorization: 'Token ' + token,
      },
    });

    if (Math.floor(response.status / 100) === 2) {
      const data = await response.json();
      return data.is_blocked;
    } else {
      console.log(await response.json());
      Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH);
    }
  } catch (error) {
    Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH);
  }
};