Skip to content

Commit

Permalink
chore: Only step the count if POST request
Browse files Browse the repository at this point in the history
- Conditionally step the count only if the request method is `POST`
- Remove the null check in the `stepCount` function and update the logic accordingly

Signed-off-by: 陳鈞 <[email protected]>
  • Loading branch information
jim60105 committed Nov 18, 2023
1 parent ee1d5d9 commit 8bff9e3
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,18 @@ export default {
* @returns A response containing the SVG badge.
*/
async fetch(request: WorkerRequest, env: Env, ctx: ExecutionContext): Promise<Response> {
// Step the count
let count: number | null = await getCountFromD1(env);
count = await stepCount(count, env);
let count: number = (await getCountFromD1(env)) || 0;
// Step the count if POST
if (request.method === 'POST') count = await stepCount(count, env);
console.log('Count', count);

return new Response('' + count, {
headers: {
'content-type': 'text/plain;charset=UTF-8',
'cache-control': 'no-cache, no-store, must-revalidate, max-age=0',
'access-control-allow-origin': '*'
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST',
'access-control-allow-headers': 'Content-Type'
}
});
}
Expand All @@ -57,7 +59,7 @@ const getCountFromD1 = async (env: Env): Promise<number | null> =>
* @param env The environment variables.
* @returns The new count.
*/
const stepCount = async (count: number | null, env: Env): Promise<number> => {
const stepCount = async (count: number, env: Env): Promise<number> => {
// If the value is null, insert a new record
if (!count) {
var result = await env.ViewCounter.prepare(
Expand All @@ -78,5 +80,5 @@ const stepCount = async (count: number | null, env: Env): Promise<number> => {
console.log('Update result', result);
}

return (count || 0) + 1;
return count + 1;
};

0 comments on commit 8bff9e3

Please sign in to comment.