Skip to content

Commit

Permalink
refactor: Use subqueries to step through the count value.
Browse files Browse the repository at this point in the history
Use subqueries to step through the count value to avoid updating the same value repeatedly when parallel requests occur.

Signed-off-by: 陳鈞 <[email protected]>
  • Loading branch information
jim60105 committed Nov 17, 2023
1 parent b723f88 commit c3322e0
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,25 +72,25 @@ const getCountFromD1 = async (env: Env): Promise<number | null> =>
const stepCount = async (count: number | null, env: Env): Promise<number> => {
// If the value is null, insert a new record
if (!count) {
count = 1;

var result = await env.ViewCounter.prepare(
'INSERT INTO ViewCounter (Name, Value) VALUES (?1, ?2)'
'INSERT INTO ViewCounter (Name, Value) VALUES (?1, 1)'
)
.bind(CounterName, count)
.bind(CounterName)
.run();

console.log('Insert result', result);
} else {
// Value++
count++;

// Update the value to D1
var result = await env.ViewCounter.prepare('UPDATE ViewCounter SET Value = ?1 WHERE Name = ?2')
.bind(count, CounterName)
// Step the count in the database
var result = await env.ViewCounter.prepare(
'UPDATE ViewCounter SET Value = (SELECT Value FROM ViewCounter WHERE Name = ?1) + 1 WHERE Name = ?1'
)
.bind(CounterName)
.run();

console.log('Update result', result);
}
return count;

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

/**
Expand Down

0 comments on commit c3322e0

Please sign in to comment.