aboutsummaryrefslogtreecommitdiff
path: root/src/services/MomentCategoryService.ts
blob: edd13ad0daf4c9226f0c3681c0c8643265822834 (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
import {Alert} from 'react-native';
import {MOMENT_CATEGORY_ENDPOINT} from '../constants';
import {ERROR_CATEGORY_CREATION} from '../constants/strings';

export const loadMomentCategories: (
  userId: string,
  token: string,
) => Promise<string[]> = async (userId, token) => {
  let categories: string[] = [];
  try {
    const response = await fetch(MOMENT_CATEGORY_ENDPOINT + `${userId}/`, {
      method: 'GET',
      headers: {
        Authorization: 'Token ' + token,
      },
    });
    const status = response.status;
    if (status === 200) {
      const data = await response.json();
      categories = data.categories;
    } else {
      return [];
    }
  } catch (err) {
    console.log(err);
    return [];
  }
  return categories;
};

export const postMomentCategories: (
  categories: string[],
  token: string,
) => Promise<number | undefined> = async (categories, token) => {
  try {
    const response = await fetch(MOMENT_CATEGORY_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Token ' + token,
      },
      body: JSON.stringify({categories}),
    });
    const status = response.status;
    const data = await response.json();
    if (status === 200) {
      return data.profile_completion_stage;
    } else {
      Alert.alert(ERROR_CATEGORY_CREATION);
      console.log('Could not post categories!');
    }
  } catch (err) {
    console.log(err);
    return undefined;
  }
  return undefined;
};