Skip to content

Commit

Permalink
#29: the basics are done
Browse files Browse the repository at this point in the history
  • Loading branch information
GalvinPython committed Apr 2, 2024
1 parent f6b98f3 commit e62fd00
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 16 deletions.
5 changes: 2 additions & 3 deletions src/components/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ const ButtonComponent = () => {
}

function clickRequest() {
// fetch("/api/clicked");
fetch('https://api-gc.galvindev.me.uk/clicked');
fetch("/api/clicked");
}

return () => {
Expand All @@ -24,7 +23,7 @@ const ButtonComponent = () => {
return (
<div>
<button id="clickButton" type="button">
<strong>Click Me! (updates my original clicker currently)</strong>
<strong>Click Me!</strong>
</button>
</div>
);
Expand Down
6 changes: 3 additions & 3 deletions src/components/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,20 @@ const CustomChart = ({ fetchClicks, clientData }: CustomChartProps) => {
const fetchData = async () => {
try {
// TODO: Change to "/clicks" when the API is set up
const response = await fetch('https://api-gc.galvindev.me.uk/clicks');
const response = await fetch('/api/clicks');
const jsonData = await response.json();

const newDataPoint = {
x: new Date().getTime(),
y: jsonData[0].row_count,
y: jsonData.clicks,
};

// 60 minutes = 3600 seconds, however 1 request every 2 seconds = 1800 datapoints for an hour
// Minus 1 for 1799 because I don't know, JavaScript moment
setData(prevData => [...prevData.slice(-1799), newDataPoint]);

// Update the odometer value
setOdometerValue(jsonData[0].row_count);
setOdometerValue(jsonData.clicks);
} catch (error) {
console.error('Error fetching data:', error);
}
Expand Down
49 changes: 48 additions & 1 deletion src/db/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,15 @@ const DB_FILE_PATH = './src/db/data/db.db';
const DB_DIRECTORY_PATH = path.dirname(DB_FILE_PATH);

let db:any;
let isInit:boolean = false;
let clicksToAdd:number = 0

function initDb() {
if (isInit) {
console.log('initDb() was called again')
return
}

export function initDb() {
// Create the directory if it doesn't exist
if (!fs.existsSync(DB_DIRECTORY_PATH)) {
fs.mkdirSync(DB_DIRECTORY_PATH, { recursive: true });
Expand Down Expand Up @@ -44,4 +51,44 @@ export function initDb() {
console.error('Error initialising database:', error);
throw error;
}
isInit = true;
}
initDb()

export async function getClicks(): Promise<string> {
return new Promise<string>((resolve, reject) => {
fs.readFile(CLICKS_FILE_PATH, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}

export async function increaseClicks() {
clicksToAdd += 1
}

setInterval(async () => {
try {
// Read the file asynchronously
const fileContents = await fs.promises.readFile(CLICKS_FILE_PATH, 'utf8');

// Parse the file contents as a number
let currentValue = parseInt(fileContents, 10);

// Add the addend to the current value
currentValue += clicksToAdd;

// Write the updated value back to the file
await fs.promises.writeFile(CLICKS_FILE_PATH, currentValue.toString(), 'utf8');

console.log(`Updated value (${currentValue}) has been written to ${CLICKS_FILE_PATH}`);
} catch (error) {
console.error('Error:', error);
throw error; // Rethrow the error to propagate it to the caller
}
clicksToAdd = 0
}, 100)
5 changes: 2 additions & 3 deletions src/pages/api/[...slugs].ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { swagger } from '@elysiajs/swagger';
import { cors } from '@elysiajs/cors';

import * as database from '../../db/database.ts'
database.initDb()

async function checkFrequencyValue(value: any) {
if ((value == 'secondly' ||
Expand Down Expand Up @@ -112,8 +111,8 @@ const app = new Elysia({ prefix: '/api' })
error: 'Not implemented'
}
})
.get('/clicks', async () => { return { clicks: 0 } })
.get('/clicked', async () => { return { clicked: true } })
.get('/clicks', async () => { return { clicks: parseInt(await database.getClicks()) } })
.get('/clicked', async () => { database.increaseClicks(); return { clicked: true } })

const handle = ({ request }: { request: Request }) => app.handle(request);

Expand Down
7 changes: 1 addition & 6 deletions src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,7 @@ import CustomChart from "../components/Chart";
<main>
<h1>Stats100 <span class="text-gradient">Clicker</span></h1>
<p class="instructions">
A new and improved Global Clicker, coming soon. (and in Astro!) <br
/>
In the meantime, my original <a href="https://gc.galvindev.me.uk"
>Clicker</a
> is still available. <br />
(this doesn't work btw)
A new and improved Global Clicker, coming soon. (and in Astro!)
</p>

<div class="b">
Expand Down

0 comments on commit e62fd00

Please # to comment.