aboutsummaryrefslogtreecommitdiff
path: root/src/services/UserFriendsServices.ts
blob: 0b138fc3eb1f8b4e77ffcf3979c41d19b558e202 (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
//Abstracted common friends api calls out here

import {Alert} from 'react-native';
import {FRIENDS_ENDPOINT} from '../constants';

export const loadFriends = async (userId: string, token: string) => {
  try {
    const response = await fetch(FRIENDS_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 friendOrUnfriendUser = async (
  user: string,
  friend: string,
  token: string,
  isFriend: boolean,
) => {
  try {
    const endpoint = FRIENDS_ENDPOINT + (isFriend ? `${user}/` : '');
    const response = await fetch(endpoint, {
      method: isFriend ? 'DELETE' : 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Token ' + token,
      },
      body: JSON.stringify({
        user,
        friend,
      }),
    });
    const status = response.status;
    if (Math.floor(status / 100) === 2) {
      return true;
    } else {
      console.log(await response.json());
      Alert.alert(
        'Something went wrong! 😭',
        "Would you believe me if I told you that I don't know what happened?",
      );
      return false;
    }
  } catch (error) {
    console.log(error);
    Alert.alert(
      'Something went wrong! 😭',
      "Would you believe me if I told you that I don't know what happened?",
    );
    return false;
  }
};