aboutsummaryrefslogtreecommitdiff
path: root/src/services/UserFollowServices.ts
blob: 105124bc674f2ec02ad06dfa135fe44c419b385a (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
93
94
95
//Abstracted common user follow api calls out here

import {Alert} from 'react-native';
import {
  FOLLOWERS_ENDPOINT,
  FOLLOW_USER_ENDPOINT,
  UNFOLLOW_USER_ENDPOINT,
  FOLLOWING_ENDPOINT,
} from '../constants';

import {ProfilePreviewType} from 'src/types';

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

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

export const followOrUnfollowUser = async (
  follower: string,
  followed: string,
  token: string,
  isFollowed: boolean,
) => {
  try {
    const endpoint = isFollowed ? UNFOLLOW_USER_ENDPOINT : FOLLOW_USER_ENDPOINT;
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        Authorization: 'Token ' + token,
      },
      body: JSON.stringify({
        follower,
        followed,
      }),
    });
    if (Math.floor(response.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;
  }
};