Новые изменения
This commit is contained in:
parent
dc00e31578
commit
e621b3c40e
8 changed files with 234 additions and 54 deletions
|
|
@ -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' } }
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue