summaryrefslogtreecommitdiff
path: root/src/redux/github/actions.js
blob: fe054a01e886e451c11267f7b40d31107ce29013 (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
import axios from 'axios';

import {
  FETCH_TRENDING_FAILED,
  FETCH_TRENDING_SUCCESS,
  PROCESS_FETCH_TRENDING,
  UPDATE_FILTERS
} from './types';

const API_URL = 'https://api.github.com/search/repositories';

const transformFilters = (filters) => {
  const transformedFilters = {};

  const reposDate = `created:${filters.dateRange.start.format('YYYY-MM-DD')}..${filters.dateRange.end.format('YYYY-MM-DD')}`;
  const reposLanguage = filters.language ? `language:${filters.language} ` : '';

  if (filters.token) {
    transformedFilters.access_token = filters.token;
  }

  transformedFilters.q = reposLanguage + reposDate;
  transformedFilters.sort = 'stars';
  transformedFilters.order = 'desc';

  return transformedFilters;
};

/**
 * @param {object} filters
 * @returns {Function}
 */
export const fetchTrending = function (filters) {
  return dispatch => {
    dispatch({ type: PROCESS_FETCH_TRENDING });

    axios.get(API_URL, {
      params: transformFilters(filters)
    }).then(response => {
      dispatch({
        type: FETCH_TRENDING_SUCCESS,
        payload: {
          start: filters.dateRange.start,
          end: filters.dateRange.end,
          data: response.data
        }
      });
    }).catch(error => {
      dispatch({
        type: FETCH_TRENDING_FAILED,
        payload: error
      });
    });
  };
};

/**
 * Updates the filters used in queries
 * @param filters
 * @return {Function}
 */
export const updateFilters = function (filters) {
  return dispatch => {
    dispatch({
      type: UPDATE_FILTERS,
      payload: filters
    });
  };
};