astro_avtourist/frontend/src/pages/api/increment-views.ts

122 lines
3.6 KiB
TypeScript
Raw Normal View History

import type { APIRoute } from 'astro';
import crypto from 'crypto';
const POCKETBASE_URL = import.meta.env.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();
}
return request.headers.get('x-real-ip') || '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 = `${POCKETBASE_URL}${path}`;
2026-04-27 20:44:02 +05:00
console.log('[Increment Views] PB Request:', method, url);
const options: RequestInit = {
method,
headers: { 'Content-Type': 'application/json' },
};
2026-04-27 20:44:02 +05:00
if (body) {
options.body = JSON.stringify(body);
console.log('[Increment Views] PB Body:', JSON.stringify(body));
}
const res = await fetch(url, options);
2026-04-27 20:44:02 +05:00
const status = res.status;
const err = await res.text();
console.log('[Increment Views] PB Response:', status, err);
if (!res.ok) {
2026-04-27 20:44:02 +05:00
throw new Error(`PB ${method} ${path}: ${status} - ${err}`);
}
2026-04-27 20:44:02 +05:00
return JSON.parse(err) || {};
}
export const POST: APIRoute = async ({ request, url }) => {
console.log('[Increment Views] PB_URL:', POCKETBASE_URL);
try {
const postId = url.searchParams.get('postId');
if (!postId || !POCKETBASE_ID_REGEX.test(postId)) {
return new Response(
JSON.stringify({ error: 'Некорректный postId' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
2026-04-27 01:04:06 +05:00
let post;
try {
post = await pbRequest('GET', `/api/collections/posts/records/${postId}`);
2026-04-27 01:04:06 +05:00
} catch {
return new Response(
JSON.stringify({ error: 'Пост не найден' }),
{ status: 404, headers: { 'Content-Type': 'application/json' } }
);
}
const ip = getClientIp(request);
const userAgent = request.headers.get('user-agent') || 'unknown';
const visitorHash = generateVisitorHash(ip, userAgent);
const now = new Date();
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const yesterdayStr = yesterday.toISOString();
2026-04-27 01:04:06 +05:00
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 };
2026-04-27 01:04:06 +05:00
} catch {
existingViews = { totalItems: 0 };
}
let isNewView = false;
2026-04-27 01:04:06 +05:00
if (existingViews.totalItems === 0) {
isNewView = true;
try {
await pbRequest('POST', '/api/collections/post_views/records', {
2026-04-27 01:04:06 +05:00
post: postId,
visitor_hash: visitorHash,
ip: ip,
user_agent: userAgent,
});
} catch {
// ignore
}
}
let totalViews = post.views || 0;
if (isNewView) {
totalViews += 1;
2026-04-27 01:04:06 +05:00
try {
await pbRequest('PATCH', `/api/collections/posts/records/${postId}`, { views: totalViews });
2026-04-27 01:04:06 +05:00
} catch {
// ignore
}
}
return new Response(
JSON.stringify({ views: totalViews, isNewView }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
);
} catch (error) {
2026-04-27 01:04:06 +05:00
console.error('[Increment Views] Error:', error);
return new Response(
JSON.stringify({ error: 'Внутренняя ошибка сервера' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
2026-04-27 01:04:06 +05:00
};