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) {
const client = new APIClient();
let result;
try {
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 { PROJECT_USER_LIST, PROJECT_LIST } from '../actions/project';
import { projectUserListSaga, projectListSaga } from './project';
import { failureActionSaga } from './failure.sagas';
export default function* rootSaga() {
yield all([
@ -10,5 +11,6 @@ export default function* rootSaga() {
takeLatest(LOGOUT_REQUEST, logoutSaga),
takeLatest(PROJECT_USER_LIST, projectUserListSaga),
takeLatest(PROJECT_LIST, projectListSaga),
takeLatest(action => /_FAILURE$/g.test(action.type), failureActionSaga),
]);
}

View File

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