website/src/routes/+layout.server.ts

32 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-10-01 04:34:07 +03:00
import { scopeCookies, visitCount, visitCountFile } from '$lib';
import { writeFileSync } from 'fs';
import { get } from 'svelte/store';
2024-10-01 02:44:39 +03:00
export const csr = true;
export const ssr = true;
2024-10-01 05:07:39 +03:00
export const prerender = 'auto';
2024-10-01 02:44:39 +03:00
export const trailingSlash = 'always';
export async function load({ cookies, url, setHeaders }) {
setHeaders({ 'Cache-Control': 'no-cache' })
const scopedCookies = scopeCookies(cookies, '/')
// parse the last visit timestamp from cookies if it exists
2024-10-01 02:44:39 +03:00
const visitedTimestamp = parseInt(scopedCookies.get('visitedTimestamp') || "0")
// get unix timestamp
2024-10-01 02:44:39 +03:00
const currentTime = new Date().getTime()
const timeSinceVisit = currentTime - visitedTimestamp
let currentVisitCount = get(visitCount)
// check if this is the first time a client is visiting or if an hour has passed since they last visited
if (visitedTimestamp === 0 || timeSinceVisit > 1000 * 60 * 60 * 24) {
// increment current and write to the store
currentVisitCount += 1; visitCount.set(currentVisitCount)
// update the cookie with the current timestamp
2024-10-01 02:44:39 +03:00
scopedCookies.set('visitedTimestamp', currentTime.toString())
// write the visit count to a file so we can load it later again
writeFileSync(visitCountFile, currentVisitCount.toString())
2024-10-01 02:44:39 +03:00
}
return {
route: url.pathname,
visitCount: currentVisitCount,
2024-10-01 02:44:39 +03:00
}
}