Skip to content

Commit

Permalink
chore: Migrate from Service Workers to ES Modules
Browse files Browse the repository at this point in the history
  • Loading branch information
jim60105 authored Oct 16, 2023
1 parent 9bbeaf6 commit 9938389
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 60 deletions.
116 changes: 62 additions & 54 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,57 +2,65 @@ const { badgen } = require('badgen');

const CounterName = 'Counter1';

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

/**
* Respond with svg badge
* @param {Request} request
*/
async function handleRequest(request) {
// Get the value from D1
let count = await ViewCounter.prepare(
'SELECT * FROM ViewCounter WHERE Name = ?1',
)
.bind(CounterName)
.first('Value');

// Value + 1, also handle the case when the value is null
++count;
console.log(count);

// Update the value to D1
var result = await db
.prepare('UPDATE ViewCounter SET Value = ?1 WHERE Name = ?2')
.bind(count, CounterName)
.run();

console.log(result);

// Get the query parameters
const { searchParams } = new URL(request.url);
let label = searchParams.get('label') || 'Views';
let labelColor = searchParams.get('labelColor') || '555';
let color = searchParams.get('color') || 'blue';
let style = searchParams.get('style') || 'flat';
let scale = searchParams.get('scale') || 1;

// Generate the svg string
const svgString = badgen({
label: label,
labelColor: labelColor,
color: color,
style: style,
scale: scale,
status: count.toString(),
});
return new Response(svgString, {
headers: {
'content-type': 'image/svg+xml;charset=utf-8',
'access-control-allow-origin': '*',
'Cache-Control':
'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
},
});
}
export default {
async fetch(request, env, ctx) {
// Get the value from D1
let count = await env.ViewCounter.prepare(
'SELECT * FROM ViewCounter WHERE Name = ?1',
)
.bind(CounterName)
.first('Value');

// 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)',
)
.bind(CounterName, count)
.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)
.run();
console.log('Update result', result);
}
console.log('Count', count);

// Get the query parameters
const { searchParams } = new URL(request.url);
let label = searchParams.get('label') || 'Views';
let labelColor = searchParams.get('labelColor') || '555';
let color = searchParams.get('color') || 'blue';
let style = searchParams.get('style') || 'flat';
let scale = searchParams.get('scale') || 1;

// Generate the svg string
const svgString = badgen({
label: label,
labelColor: labelColor,
color: color,
style: style,
scale: scale,
status: count.toString(),
});
console.log('SVG', svgString);

return new Response(svgString, {
headers: {
'content-type': 'image/svg+xml;charset=utf-8',
'access-control-allow-origin': '*',
'Cache-Control':
'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
},
});
},
};
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
"description": "A template for kick starting a Cloudflare Workers project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"format": "prettier --write '**/*.{js,css,json,md}'"
"deploy": "export NO_D1_WARNING=true && wrangler deploy",
"dev": "wrangler dev",
"format": "prettier --config .prettierrc.json --write **/*.{ts,js}"
},
"author": "Aveek Saha <[email protected]>",
"license": "MIT",
Expand Down
3 changes: 2 additions & 1 deletion wrangler.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
name = "view-counter"

compatibility_date = "2023-10-16"
compatibility_date = "2023-07-24"
main = "index.js"

send_metrics = false
workers_dev = true

[[d1_databases]]
Expand Down

0 comments on commit 9938389

Please sign in to comment.