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

main
Last change on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

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