Ajout APIClient

This commit is contained in:
wpetit 2020-02-25 10:14:21 +01:00
parent 0a21001a0a
commit 88e8a8b8a3
2 changed files with 57 additions and 26 deletions

View File

@ -1,11 +1,13 @@
import { call, put } from 'redux-saga/effects';
import { loginFailure, loginSuccess, logoutFailure, logoutSuccess } from '../actions/auth.actions';
import { addMessage } from '../actions/message.actions';
import { APIClient } from '../services/api-client.service.js';
export function* loginSaga(action) {
const client = new APIClient();
let result;
try {
result = yield call(doLogin, action.username, action.password);
result = yield call(client.login, action.username, action.password);
} catch(err) {
yield put(loginFailure(action.username, err));
yield put(addMessage('danger', "Une erreur inconnue bloque le fonctionnement normal de l'application. Veuillez réessayer plus tard."));
@ -22,25 +24,11 @@ export function* loginSaga(action) {
yield put(loginSuccess(action.username));
}
function doLogin(username, password) {
return fetch('http://localhost:8001/api/v1/login', {
method: 'POST',
body: JSON.stringify({
username: username,
password: password
}),
headers: {
'Content-Type': 'application/json',
},
mode: 'cors',
credentials: 'include'
}).then(res => res.json())
}
export function* logoutSaga(action) {
let result;
try {
result = yield call(doLogout);
result = yield call(client.logout);
} catch(err) {
yield put(logoutFailure(err));
yield put(addMessage('danger', "Une erreur inconnue bloque le fonctionnement normal de l'application. Veuillez réessayer plus tard."));
@ -57,13 +45,3 @@ export function* logoutSaga(action) {
yield put(logoutSuccess(action.username));
}
function doLogout() {
return fetch('http://localhost:8001/api/v1/logout', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
mode: 'cors',
credentials: 'include'
}).then(res => res.json())
}

View File

@ -0,0 +1,53 @@
export class APIClient {
constructor(baseURL = 'http://localhost:8001/api/v1') {
this.baseURL = baseURL;
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
this.me = this.me.bind(this);
this.listUsers = this.listUsers.bind(this);
this.listRequests = this.listRequests.bind(this);
}
login(username, password) {
return this._callAPI('/login', { username, password }, 'POST')
}
logout() {
return this._callAPI('/logout')
}
me() {
return this._callAPI('/me')
}
listUsers() {
return this._callAPI('/users')
}
listRequests() {
}
createRequest(request) {
}
updateRequestStatus(reqID, newStatus) {
}
_callAPI(path, body, method='GET') {
return fetch(baseURL + path, {
method,
headers: {
'Content-Type': 'application/json',
},
mode: 'cors',
credentials: true,
body: JSON.stringify(body),
})
.then(res => res.json())
}
}