Новые изменения

This commit is contained in:
Web-serfer 2026-04-27 01:04:06 +05:00
parent dc00e31578
commit e621b3c40e
8 changed files with 234 additions and 54 deletions

View file

@ -314,20 +314,15 @@ const {
const viewsEl = document.querySelector('.meta-views') as HTMLElement & { dataset: { postId: string } };
if (viewsEl?.dataset?.postId) {
const postId = viewsEl.dataset.postId;
const hasViewed = sessionStorage.getItem(`viewed_${postId}`);
if (!hasViewed) {
fetch(`/api/increment-views?postId=${postId}`, { method: 'POST' })
.then(res => res.json())
.then(data => {
if (data.views !== undefined) {
viewsEl.textContent = formatViews(data.views);
}
})
.catch(() => {});
sessionStorage.setItem(`viewed_${postId}`, 'true');
}
fetch(`/api/increment-views?postId=${postId}`, { method: 'POST' })
.then(res => res.json())
.then(data => {
if (data.views !== undefined) {
viewsEl.textContent = formatViews(data.views);
}
})
.catch(() => {});
}
function formatViews(n: number): string {

View file

@ -0,0 +1,16 @@
import PocketBase from 'pocketbase';
const PB_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';
const PB_ADMIN_EMAIL = import.meta.env.PB_ADMIN_EMAIL || 'admin@example.com';
const PB_ADMIN_PASSWORD = import.meta.env.PB_ADMIN_PASSWORD || 'admin_password';
const pbServer = new PocketBase(PB_URL);
export { pbServer };
export async function initPbServer() {
if (!pbServer.authStore.isValid) {
await pbServer.collection('_superusers').authWithPassword(PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD);
}
return pbServer;
}

View file

@ -1,7 +1,6 @@
import type { APIRoute } from 'astro';
import crypto from 'crypto';
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';
import { initPbServer } from '@lib/pbServer';
const POCKETBASE_ID_REGEX = /^[a-z0-9]{15}$/;
@ -19,6 +18,8 @@ function generateVisitorHash(ip: string, userAgent: string): string {
export const POST: APIRoute = async ({ request, url }) => {
try {
const pb = await initPbServer();
const postId = url.searchParams.get('postId');
if (!postId || !POCKETBASE_ID_REGEX.test(postId)) {
@ -28,19 +29,16 @@ export const POST: APIRoute = async ({ request, url }) => {
);
}
const postRes = await fetch(
`${POCKETBASE_URL}/api/collections/posts/records/${postId}`,
);
if (!postRes.ok) {
let post;
try {
post = await pb.collection('posts').getOne(postId);
} catch {
return new Response(
JSON.stringify({ error: 'Пост не найден' }),
{ status: 404, headers: { 'Content-Type': 'application/json' } }
);
}
const post = await postRes.json();
const ip = getClientIp(request);
const userAgent = request.headers.get('user-agent') || 'unknown';
const visitorHash = generateVisitorHash(ip, userAgent);
@ -49,33 +47,29 @@ export const POST: APIRoute = async ({ request, url }) => {
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const yesterdayStr = yesterday.toISOString();
const existingViewRes = await fetch(
`${POCKETBASE_URL}/api/collections/post_views/records?` +
new URLSearchParams({
let existingViews;
try {
existingViews = await pb.collection('post_views').getList(1, 1, {
filter: `post="${postId}" && visitor_hash="${visitorHash}" && created >= "${yesterdayStr}"`,
})
);
});
} catch {
existingViews = { totalItems: 0 };
}
let isNewView = false;
if (existingViewRes.ok) {
const existingData = await existingViewRes.json();
if (existingData.items?.length === 0) {
isNewView = true;
if (existingViews.totalItems === 0) {
isNewView = true;
await fetch(
`${POCKETBASE_URL}/api/collections/post_views/records`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
post: postId,
visitor_hash: visitorHash,
ip: ip,
user_agent: userAgent,
}),
}
);
try {
await pb.collection('post_views').create({
post: postId,
visitor_hash: visitorHash,
ip: ip,
user_agent: userAgent,
});
} catch {
// ignore
}
}
@ -84,14 +78,11 @@ export const POST: APIRoute = async ({ request, url }) => {
if (isNewView) {
totalViews += 1;
await fetch(
`${POCKETBASE_URL}/api/collections/posts/records/${postId}`,
{
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ views: totalViews }),
}
);
try {
await pb.collection('posts').update(postId, { views: totalViews });
} catch {
// ignore
}
}
return new Response(
@ -100,10 +91,10 @@ export const POST: APIRoute = async ({ request, url }) => {
);
} catch (error) {
console.error('[Increment Views API] Error:', error);
console.error('[Increment Views] Error:', error);
return new Response(
JSON.stringify({ error: 'Внутренняя ошибка сервера' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
};
};