generated from dwd/boilarplate-astro-tailwind
edit news last worked
This commit is contained in:
70
public/js/js-0.1.0.js
Normal file
70
public/js/js-0.1.0.js
Normal file
@@ -0,0 +1,70 @@
|
||||
function getCookie(cname) {
|
||||
let name = cname + "=";
|
||||
let ca = document.cookie.split(';');
|
||||
for (let i = 0; i < ca.length; i++) {
|
||||
let c = ca[i];
|
||||
while (c.charAt(0) == ' ') {
|
||||
c = c.substring(1);
|
||||
}
|
||||
if (c.indexOf(name) == 0) {
|
||||
const cookieValue = c.substring(name.length, c.length);
|
||||
// console.log(`Cookie ${cname} found with value: ${cookieValue}`);
|
||||
return cookieValue;
|
||||
}
|
||||
}
|
||||
// console.log(`Cookie ${cname} not found`);
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
function makeProtectedRequest(apiUrl, renewUrl, access_token, formData) {
|
||||
|
||||
return fetch(apiUrl, {
|
||||
method: 'POST',
|
||||
// mode: "cors",
|
||||
headers: {
|
||||
// 'Authorization': `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
// credentials: 'same-origin',
|
||||
body: JSON.stringify(formData),
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Request failed');
|
||||
} else if(response.status === 204) {
|
||||
// Token is expired or invalid, trigger refresh
|
||||
// console.log(access_token)
|
||||
return renewToken(renewUrl, access_token).then(access_token_new => {
|
||||
// Retry the original request with the new token
|
||||
// console.log("formData :" +access_token_new)
|
||||
formData.access_token=access_token_new;
|
||||
return fetch(apiUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
// 'Authorization': `Bearer ${newAccessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
});
|
||||
}
|
||||
|
||||
function renewToken(renewUrl, access_token) {
|
||||
return fetch(renewUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ tokenToRenew: access_token }),
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.cookie = `access_token=${data.access_token}; path=/`;
|
||||
// console.log('New Access Token:', data);
|
||||
return data.access_token;
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user