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 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}$/;
@ -16,15 +17,26 @@ 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}`;
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();
}
export const POST: APIRoute = async ({ request, url }) => {
console.log('[Increment Views] PB_URL:', POCKETBASE_URL);
try {
console.log('[Increment Views] PB_URL:', import.meta.env.POCKETBASE_URL);
console.log('[Increment Views] PB_ADMIN_EMAIL:', import.meta.env.PB_ADMIN_EMAIL);
console.log('[Increment Views] PB_ADMIN_PASSWORD:', import.meta.env.PB_ADMIN_PASSWORD ? '***SET***' : '***NOT SET***');
console.log('[Increment Views] Calling initPbServer...');
const pb = await initPbServer();
console.log('[Increment Views] initPbServer done, auth valid:', pb.authStore.isValid);
const postId = url.searchParams.get('postId');
if (!postId || !POCKETBASE_ID_REGEX.test(postId)) {
@ -36,7 +48,7 @@ export const POST: APIRoute = async ({ request, url }) => {
let post;
try {
post = await pb.collection('posts').getOne(postId);
post = await pbRequest('GET', `/api/collections/posts/records/${postId}`);
} catch {
return new Response(
JSON.stringify({ error: 'Пост не найден' }),
@ -54,9 +66,8 @@ export const POST: APIRoute = async ({ request, url }) => {
let existingViews;
try {
existingViews = await pb.collection('post_views').getList(1, 1, {
filter: `post="${postId}" && visitor_hash="${visitorHash}" && created >= "${yesterdayStr}"`,
});
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 };
}
@ -67,7 +78,7 @@ export const POST: APIRoute = async ({ request, url }) => {
isNewView = true;
try {
await pb.collection('post_views').create({
await pbRequest('POST', '/api/collections/post_views/records', {
post: postId,
visitor_hash: visitorHash,
ip: ip,
@ -84,7 +95,7 @@ export const POST: APIRoute = async ({ request, url }) => {
totalViews += 1;
try {
await pb.collection('posts').update(postId, { views: totalViews });
await pbRequest('PATCH', `/api/collections/posts/records/${postId}`, { views: totalViews });
} catch {
// ignore
}