UserForm: ajout retour de validation d'API

This commit is contained in:
2020-03-09 11:32:21 +01:00
parent de6832e94f
commit 67732aa00a
11 changed files with 163 additions and 19 deletions

View File

@ -1,4 +1,5 @@
import { UnauthorizedError } from '../errors/unauthorized.error.js';
import { APIError } from '../errors/api.error.js';
export const UnauthorizedStatusCode = 401;
@ -10,10 +11,12 @@ export class APIClient {
this.retrieveSessionUser = this.retrieveSessionUser.bind(this);
this.listUsers = this.listUsers.bind(this);
this.listRequests = this.listRequests.bind(this);
this.createUser = this.createUser.bind(this);
}
login(username, password) {
return this._callAPI('/login', { username, password }, 'POST')
return this._callAPI('/login', { username, password }, 'POST')
.then(result => result.data);
}
logout() {
@ -21,7 +24,8 @@ export class APIClient {
}
retrieveSessionUser() {
return this._callAPI('/me')
return this._callAPI('/me')
.then(result => result.data);
}
listUsers() {
@ -36,6 +40,12 @@ export class APIClient {
}
createUser(username, password) {
return this._callAPI('/users', { username, password }, 'POST')
.then(this._withAPIErrorMiddleware('create_user'))
.then(result => result.data);
}
updateRequestStatus(reqID, newStatus) {
}
@ -50,13 +60,27 @@ export class APIClient {
credentials: 'include',
body: JSON.stringify(body),
})
.then(res => {
if (res.status === UnauthorizedStatusCode) {
throw new UnauthorizedError();
}
return res;
})
.then(this._withUnauthorizedErrorMiddleware())
.then(res => res.json())
}
_withUnauthorizedErrorMiddleware() {
return res => {
if (res.status === UnauthorizedStatusCode) {
throw new UnauthorizedError();
}
return res;
}
}
_withAPIErrorMiddleware(endpoint) {
return result => {
if (result.error) {
const { code, message, data } = result.error;
throw new APIError(endpoint, code, message, data);
}
return result;
}
}
}