Use direct fetch instead of PocketBase SDK to avoid auth issues

This commit is contained in:
Web-serfer 2026-04-27 20:37:55 +05:00
parent 35e59b5f8c
commit 4cb5848098

View file

@ -1,6 +1,7 @@
import type { APIRoute } from 'astro'; import type { APIRoute } from 'astro';
import crypto from 'crypto'; import crypto from 'crypto';
import { initPbServer } from '@lib/pbServer';
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';
const POCKETBASE_ID_REGEX = /^[a-z0-9]{15}$/; const POCKETBASE_ID_REGEX = /^[a-z0-9]{15}$/;
@ -16,15 +17,26 @@ function generateVisitorHash(ip: string, userAgent: string): string {
return crypto.createHash('sha256').update(ip + userAgent).digest('hex').slice(0, 32); return crypto.createHash('sha256').update(ip + userAgent).digest('hex').slice(0, 32);
} }
export const POST: APIRoute = async ({ request, url }) => { async function pbRequest(method: string, path: string, body?: object) {
try { const url = `${POCKETBASE_URL}${path}`;
console.log('[Increment Views] PB_URL:', import.meta.env.POCKETBASE_URL); const options: RequestInit = {
console.log('[Increment Views] PB_ADMIN_EMAIL:', import.meta.env.PB_ADMIN_EMAIL); method,
console.log('[Increment Views] PB_ADMIN_PASSWORD:', import.meta.env.PB_ADMIN_PASSWORD ? '***SET***' : '***NOT SET***'); headers: { 'Content-Type': 'application/json' },
console.log('[Increment Views] Calling initPbServer...'); };
const pb = await initPbServer(); if (body) options.body = JSON.stringify(body);
console.log('[Increment Views] initPbServer done, auth valid:', pb.authStore.isValid);
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();
}
export const POST: APIRoute = async ({ request, url }) => {
console.log('[Increment Views] PB_URL:', POCKETBASE_URL);
try {
const postId = url.searchParams.get('postId'); const postId = url.searchParams.get('postId');
if (!postId || !POCKETBASE_ID_REGEX.test(postId)) { if (!postId || !POCKETBASE_ID_REGEX.test(postId)) {
@ -36,7 +48,7 @@ export const POST: APIRoute = async ({ request, url }) => {
let post; let post;
try { try {
post = await pb.collection('posts').getOne(postId); post = await pbRequest('GET', `/api/collections/posts/records/${postId}`);
} catch { } catch {
return new Response( return new Response(
JSON.stringify({ error: 'Пост не найден' }), JSON.stringify({ error: 'Пост не найден' }),
@ -54,9 +66,8 @@ export const POST: APIRoute = async ({ request, url }) => {
let existingViews; let existingViews;
try { try {
existingViews = await pb.collection('post_views').getList(1, 1, { const res = await pbRequest('GET', `/api/collections/post_views/records?filter=(post="${postId}")&&(visitor_hash="${visitorHash}")&&(created>="${yesterdayStr}")&perPage=1`);
filter: `post="${postId}" && visitor_hash="${visitorHash}" && created >= "${yesterdayStr}"`, existingViews = { totalItems: res.totalItems || 0 };
});
} catch { } catch {
existingViews = { totalItems: 0 }; existingViews = { totalItems: 0 };
} }
@ -67,7 +78,7 @@ export const POST: APIRoute = async ({ request, url }) => {
isNewView = true; isNewView = true;
try { try {
await pb.collection('post_views').create({ await pbRequest('POST', '/api/collections/post_views/records', {
post: postId, post: postId,
visitor_hash: visitorHash, visitor_hash: visitorHash,
ip: ip, ip: ip,
@ -84,7 +95,7 @@ export const POST: APIRoute = async ({ request, url }) => {
totalViews += 1; totalViews += 1;
try { try {
await pb.collection('posts').update(postId, { views: totalViews }); await pbRequest('PATCH', `/api/collections/posts/records/${postId}`, { views: totalViews });
} catch { } catch {
// ignore // ignore
} }