url.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import axios from 'axios';
  2. import cookie from 'js-cookie';
  3. import {
  4. ADD_URL,
  5. LIST_URLS,
  6. UPDATE_URL_LIST,
  7. DELETE_URL,
  8. SHORTENER_LOADING,
  9. TABLE_LOADING,
  10. SHORTENER_ERROR,
  11. } from './actionTypes';
  12. const addUrl = payload => ({ type: ADD_URL, payload });
  13. const listUrls = payload => ({ type: LIST_URLS, payload });
  14. const updateUrlList = payload => ({ type: UPDATE_URL_LIST, payload });
  15. const deleteUrl = payload => ({ type: DELETE_URL, payload });
  16. const showTableLoading = () => ({ type: TABLE_LOADING });
  17. export const setShortenerFormError = payload => ({
  18. type: SHORTENER_ERROR,
  19. payload,
  20. });
  21. export const showShortenerLoading = () => ({ type: SHORTENER_LOADING });
  22. export const createShortUrl = params => async dispatch => {
  23. try {
  24. const { data } = await axios.post('/api/url/submit', params, {
  25. headers: { Authorization: cookie.get('token') },
  26. });
  27. dispatch(addUrl(data));
  28. } catch ({ response }) {
  29. dispatch(setShortenerFormError(response.data.error));
  30. }
  31. };
  32. export const getUrlsList = params => async (dispatch, getState) => {
  33. if (params) {
  34. dispatch(updateUrlList(params));
  35. }
  36. dispatch(showTableLoading());
  37. const { url } = getState();
  38. const { list, ...queryParams } = url;
  39. const query = Object.keys(queryParams).reduce(
  40. (string, item) => `${string + item}=${queryParams[item]}&`,
  41. '?'
  42. );
  43. try {
  44. const { data } = await axios.get(`/api/url/geturls${query}`, {
  45. headers: { Authorization: cookie.get('token') },
  46. });
  47. dispatch(listUrls(data));
  48. } catch (error) {
  49. //
  50. }
  51. };
  52. export const deleteShortUrl = params => async dispatch => {
  53. dispatch(showTableLoading());
  54. try {
  55. await axios.post('/api/url/deleteurl', params, {
  56. headers: { Authorization: cookie.get('token') },
  57. });
  58. dispatch(deleteUrl(params.id));
  59. } catch ({ response }) {
  60. dispatch(setShortenerFormError(response.data.error));
  61. }
  62. };