Ajout saga gestion des actions de type '*_FAILURE'

This commit is contained in:
wpetit 2020-02-25 10:46:17 +01:00
parent 8ba45f84cb
commit edcd4343eb
5 changed files with 31 additions and 1 deletions

View File

@ -0,0 +1,6 @@
export class UnauthorizedError extends Error {
constructor() {
super("Unauthorized");
Error.captureStackTrace(this, UnauthorizedError);
}
}

View File

@ -27,6 +27,7 @@ export function* loginSaga(action) {
export function* logoutSaga(action) { export function* logoutSaga(action) {
const client = new APIClient();
let result; let result;
try { try {
result = yield call(client.logout); result = yield call(client.logout);

View File

@ -0,0 +1,12 @@
import { put } from 'redux-saga/effects';
import { UnauthorizedError } from '../errors/unauthorized.error.js';
import { addMessage } from '../actions/message.actions.js';
import { logout } from '../actions/auth.actions.js';
export function* failureActionSaga({ error }) {
console.error(error);
if (error instanceof UnauthorizedError) {
yield put(addMessage('danger', 'Vous avez été déconnecté.'));
yield put(logout());
}
}

View File

@ -3,6 +3,7 @@ import { LOGIN_REQUEST, LOGOUT_REQUEST } from '../actions/auth.actions';
import { loginSaga, logoutSaga } from './auth.sagas'; import { loginSaga, logoutSaga } from './auth.sagas';
import { PROJECT_USER_LIST, PROJECT_LIST } from '../actions/project'; import { PROJECT_USER_LIST, PROJECT_LIST } from '../actions/project';
import { projectUserListSaga, projectListSaga } from './project'; import { projectUserListSaga, projectListSaga } from './project';
import { failureActionSaga } from './failure.sagas';
export default function* rootSaga() { export default function* rootSaga() {
yield all([ yield all([
@ -10,5 +11,6 @@ export default function* rootSaga() {
takeLatest(LOGOUT_REQUEST, logoutSaga), takeLatest(LOGOUT_REQUEST, logoutSaga),
takeLatest(PROJECT_USER_LIST, projectUserListSaga), takeLatest(PROJECT_USER_LIST, projectUserListSaga),
takeLatest(PROJECT_LIST, projectListSaga), takeLatest(PROJECT_LIST, projectListSaga),
takeLatest(action => /_FAILURE$/g.test(action.type), failureActionSaga),
]); ]);
} }

View File

@ -1,3 +1,6 @@
import { UnauthorizedError } from '../errors/unauthorized.error.js';
export const UnauthorizedStatusCode = 401;
export class APIClient { export class APIClient {
constructor(baseURL = 'http://localhost:8001/api/v1') { constructor(baseURL = 'http://localhost:8001/api/v1') {
@ -47,6 +50,12 @@ export class APIClient {
credentials: 'include', credentials: 'include',
body: JSON.stringify(body), body: JSON.stringify(body),
}) })
.then(res => {
if (res.status === UnauthorizedStatusCode) {
throw new UnauthorizedError();
}
return res;
})
.then(res => res.json()) .then(res => res.json())
} }