[d565449] | 1 | import config from "./netconfig.js";
|
---|
| 2 |
|
---|
| 3 |
|
---|
| 4 | class HttpService {
|
---|
[0c6b92a] | 5 | constructor(auth = false) {
|
---|
[d565449] | 6 | this.auth = auth;
|
---|
| 7 | }
|
---|
| 8 |
|
---|
| 9 | setAuthenticated(){
|
---|
| 10 | this.auth = true;
|
---|
| 11 | }
|
---|
| 12 |
|
---|
| 13 | async request(method, endpoint, data = null) {
|
---|
| 14 | const options = {
|
---|
| 15 | method: method,
|
---|
| 16 | headers: {
|
---|
| 17 | 'Content-Type': 'application/json',
|
---|
| 18 | },
|
---|
| 19 | };
|
---|
| 20 |
|
---|
| 21 | if (this.auth) {
|
---|
| 22 | const token = localStorage.getItem("token");
|
---|
| 23 | if (token) {
|
---|
| 24 | options.headers['Authorization'] = `Bearer ${token}`;
|
---|
| 25 | } else {
|
---|
| 26 | throw new Error("No token found!");
|
---|
| 27 | }
|
---|
| 28 | }
|
---|
| 29 |
|
---|
| 30 | if (data) {
|
---|
| 31 | options.body = JSON.stringify(data);
|
---|
| 32 | }
|
---|
| 33 |
|
---|
[0c6b92a] | 34 | const response = await fetch(`${endpoint}`, options);
|
---|
[d565449] | 35 |
|
---|
| 36 | if (!response.ok) {
|
---|
| 37 | switch (response.status) {
|
---|
| 38 | case 401:
|
---|
| 39 | console.log("Unauthorized: Invalid token or session expired");
|
---|
| 40 | break;
|
---|
| 41 | case 403:
|
---|
| 42 | console.log("Forbidden: You don't have permission to access this resource");
|
---|
| 43 | window.location.href = "/Login";
|
---|
| 44 | break;
|
---|
| 45 | case 500:
|
---|
| 46 | console.log("Server error: Try again later");
|
---|
| 47 | break;
|
---|
| 48 | default:
|
---|
| 49 | console.log(`Unexpected error: ${response.status}`);
|
---|
| 50 | }
|
---|
| 51 | throw new Error(`Error! status: ${response.status}`);
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | console.log("HTTPSERVICE: RESPONSE:",response);
|
---|
| 55 |
|
---|
| 56 | return response.json();
|
---|
| 57 | }
|
---|
| 58 |
|
---|
| 59 | get(endpoint) {
|
---|
| 60 | return this.request('GET', endpoint);
|
---|
| 61 | }
|
---|
| 62 |
|
---|
| 63 | post(endpoint, data) {
|
---|
| 64 | return this.request('POST', endpoint, data);
|
---|
| 65 | }
|
---|
| 66 |
|
---|
| 67 | put(endpoint, data) {
|
---|
| 68 | return this.request('PUT', endpoint, data);
|
---|
| 69 | }
|
---|
| 70 |
|
---|
| 71 | delete(endpoint) {
|
---|
| 72 | return this.request('DELETE', endpoint);
|
---|
| 73 | }
|
---|
| 74 | }
|
---|
| 75 |
|
---|
| 76 | export default HttpService;
|
---|
| 77 | |
---|