opt: упростить счетчики - одна запись в БД вместо тысяч

- site_stats: 1 запись с полями today/total вместо site_visitors
- posts: today_views + last_reset вместо post_views коллекции
- Удалены старые коллекции site_visitors и post_views
This commit is contained in:
Web-serfer 2026-05-07 16:55:35 +05:00
parent 62a6453a1a
commit e7700a3391
6 changed files with 65 additions and 622 deletions

View file

@ -1,44 +1,8 @@
import type { APIRoute } from 'astro';
import crypto from 'crypto';
const PB_POCKETBASE_URL = import.meta.env.PB_POCKETBASE_URL || 'http://127.0.0.1:8090';
const POCKETBASE_ID_REGEX = /^[a-z0-9]{15}$/;
function getClientIp(request: Request): string {
const forwarded = request.headers.get('x-forwarded-for');
if (forwarded) {
return forwarded.split(',')[0].trim();
}
const realIp = request.headers.get('x-real-ip');
if (realIp) {
return realIp;
}
// Для localhost использовать заголовок Host или default
const host = request.headers.get('host') || 'localhost';
return host.includes('localhost') || host.includes('127.0.0.1') ? 'localhost' : 'unknown';
}
function generateVisitorHash(ip: string, userAgent: string): string {
return crypto.createHash('sha256').update(ip + userAgent).digest('hex').slice(0, 32);
}
async function pbRequest(method: string, path: string, body?: object) {
const url = `${PB_POCKETBASE_URL}${path}`;
const options: RequestInit = {
method,
headers: { 'Content-Type': 'application/json' },
};
if (body) options.body = JSON.stringify(body);
const res = await fetch(url, options);
if (!res.ok) {
const err = await res.text();
throw new Error(`PB ${method} ${path}: ${res.status} - ${err}`);
}
return res.json();
}
function jsonResponse(data: object, status = 200): Response {
return new Response(JSON.stringify(data), {
status,
@ -46,7 +10,7 @@ function jsonResponse(data: object, status = 200): Response {
});
}
export const GET: APIRoute = async ({ request, url }) => {
export const GET: APIRoute = async ({ url }) => {
try {
const postId = url.searchParams.get('postId');
@ -54,59 +18,43 @@ export const GET: APIRoute = async ({ request, url }) => {
return jsonResponse({ error: 'Некорректный postId' }, 400);
}
// Получаем пост
let post;
try {
post = await pbRequest('GET', `/api/collections/posts/records/${postId}`);
post = await fetch(`${PB_POCKETBASE_URL}/api/collections/posts/records/${postId}`, {
headers: { 'Content-Type': 'application/json' }
}).then(r => r.json());
} catch {
return jsonResponse({ error: 'Пост не найден' }, 404);
}
const ip = getClientIp(request);
const userAgent = request.headers.get('user-agent') || 'unknown';
const visitorHash = generateVisitorHash(ip, userAgent);
if (!post || !post.id) {
return jsonResponse({ error: 'Пост не найден' }, 404);
}
const now = new Date();
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const yesterdayStr = yesterday.toISOString();
const todayStr = now.toISOString().split('T')[0];
let existingViews;
try {
const res = await pbRequest('GET', `/api/collections/post_views/records?filter=(post="${postId}")&&(visitor_hash="${visitorHash}")&&(created>="${yesterdayStr}")&perPage=1`);
existingViews = { totalItems: res.totalItems || 0 };
} catch {
existingViews = { totalItems: 0 };
let { views = 0, today_views = 0, last_reset = '' } = post;
// Если новый день - сбрасываем today_views
if (last_reset !== todayStr) {
today_views = 0;
last_reset = todayStr;
}
let isNewView = false;
// Инкремент
views++;
today_views++;
if (existingViews.totalItems === 0) {
isNewView = true;
// Обновляем пост
await fetch(`${PB_POCKETBASE_URL}/api/collections/posts/records/${postId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ views, today_views, last_reset })
});
try {
await pbRequest('POST', '/api/collections/post_views/records', {
post: postId,
visitor_hash: visitorHash,
ip: ip,
user_agent: userAgent,
});
} catch {
// ignore
}
}
let totalViews = post.views || 0;
if (isNewView) {
totalViews += 1;
try {
await pbRequest('PATCH', `/api/collections/posts/records/${postId}`, { views: totalViews });
} catch {
// ignore
}
}
return jsonResponse({ views: totalViews, isNewView }, 200);
return jsonResponse({ views, today_views }, 200);
} catch (error) {
console.error('[Increment Views] Error:', error);