source: imaps-frontend/src/scripts/net/HttpService.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

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