saga.ts 1.44 KB
Newer Older
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
1
import { all, takeEvery, select, call, put } from 'redux-saga/effects';
2
import { ApiCall } from '@gringlobal/client/model/common';
3
4
5

import { coreSagas } from '@gringlobal/client/action/saga';

Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
6
import { cooperatorPublicSagas } from 'cooperator/action/public';
7
8
9
10
11
12
import { userPublicSagas } from 'user/action/public';


export default function*() {
  yield all([
    ...coreSagas,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
13
    ...cooperatorPublicSagas,
14
    ...userPublicSagas,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
15

16
17
    // if action has method
    takeEvery((action) => action.type === 'API' && !! action.method, appendAxiosConfig),
18
19
  ]);
}
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
20
21

function *appendAxiosConfig(action) {
22
  console.log(`Appeding axios config for ${action.target}`);
23
24
  yield put({ type: action.target, payload: { apiCall: ApiCall.start() } }); // Loading

Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
25
26
27
28
29
30
31
32
33
  const accessToken = yield select((state) => state.login.access_token);

  const xhrConfig: any = {
    headers: {
      common: {
        Authorization: `Bearer ${accessToken}`,
      },
    },
  };
Oleksii Savran's avatar
Oleksii Savran committed
34
35
36
37
38
39
  try {
    let resp = yield call(action.method, ...action.params, xhrConfig);
    if (action.onSuccess) {
      resp = action.onSuccess(resp); // postprocess
    }
    yield put({ type: action.target, payload: { apiCall: ApiCall.success(resp) } });
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
40
41
  } catch (error) {
    console.log('Api error while requesting: ', error.response);
Oleksii Savran's avatar
Oleksii Savran committed
42
    if (action.onFail) {
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
43
      action.onFail(error); // postprocess
Oleksii Savran's avatar
Oleksii Savran committed
44
    }
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
45
46
    yield put({ type: action.target, payload: { apiCall: ApiCall.error(error) } });
    throw error.response;
47
  }
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
48
}