Skip to content

Commit

Permalink
Improved error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
L480 committed Mar 7, 2024
1 parent 5ae7114 commit 3cc163d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
21 changes: 18 additions & 3 deletions workers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ export default {
};
let allTonies = [];

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 @@ -25,7 +34,10 @@ export default {
},
cf: cf
});
const tokenResponse = await tokenRequest.json();
const tokenResponse = await gatherResponse(tokenRequest);
if (tokenRequest.status != 200) {
console.error(tokenResponse);
}
await env.kv.put('REFRESH_TOKEN', tokenResponse.refresh_token);

// Get tonies
Expand All @@ -39,7 +51,10 @@ export default {
},
cf: cf
});
const graphqlResponse = await graphqlRequest.json();
const graphqlResponse = await gatherResponse(graphqlRequest);
if (graphqlRequest.status != 200) {
console.error(graphqlResponse);
}

// Parse content tonies
const contentTonies = graphqlResponse.data.households[0].contentTonies;
Expand All @@ -56,7 +71,7 @@ export default {
// JSON response with cache and CORS
const response = new Response(JSON.stringify(allTonies));
response.headers.set('Cache-Control', 'max-age=' + cacheTtl);
response.headers.set('Access-Control-Allow-Origin', 'https://tildas-tonies.de');
response.headers.set('Access-Control-Allow-Origin', env.CORS_ORIGINS);
return response;
},
};
6 changes: 5 additions & 1 deletion workers/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ route = { pattern = "api.tildas-tonies.de", custom_domain = true }
kv_namespaces = [
{ binding = "kv", id = "__CLOUDFLARE_KV_ID__" }
]

[triggers]
crons = ["0 13 * * sat"]
crons = ["0 13 * * sat"] # To keep the access token fresh when no one is accessing the page.

[vars]
CORS_ORIGINS = "https://tildas-tonies.de"

0 comments on commit 3cc163d

Please sign in to comment.