Skip to content

Commit

Permalink
Update index.js
Browse files Browse the repository at this point in the history
  • Loading branch information
L480 authored Mar 6, 2024
1 parent 4962151 commit 5ae7114
Showing 1 changed file with 4 additions and 18 deletions.
22 changes: 4 additions & 18 deletions workers/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export default {
async scheduled(event, env, ctx) {
await this.fetch(event, env, ctx);
await this.fetch(event, env, ctx); // To keep the access token fresh when no one is accessing the page.
},
async fetch(request, env, ctx) {
const tokenEndpoint = 'https://login.tonies.com/auth/realms/tonies/protocol/openid-connect/token';
Expand All @@ -15,20 +15,6 @@ export default {
};
let allTonies = [];

/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
async function gatherResponse(response) {
const { headers } = response;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return await response.json();
}
return response.text();
}

// Get access token and save new refresh token to KV
const tokenRequest = await fetch(tokenEndpoint, {
body: tokenBody,
Expand All @@ -39,7 +25,7 @@ export default {
},
cf: cf
});
const tokenResponse = await gatherResponse(tokenRequest);
const tokenResponse = await tokenRequest.json();
await env.kv.put('REFRESH_TOKEN', tokenResponse.refresh_token);

// Get tonies
Expand All @@ -53,7 +39,7 @@ export default {
},
cf: cf
});
const graphqlResponse = await gatherResponse(graphqlRequest);
const graphqlResponse = await graphqlRequest.json();

// Parse content tonies
const contentTonies = graphqlResponse.data.households[0].contentTonies;
Expand All @@ -73,4 +59,4 @@ export default {
response.headers.set('Access-Control-Allow-Origin', 'https://tildas-tonies.de');
return response;
},
};
};

0 comments on commit 5ae7114

Please sign in to comment.