astro_avtourist/frontend/src/lib/pb.ts

74 lines
No EOL
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import PocketBase from 'pocketbase';
const PB_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';
export const pb = new PocketBase(PB_URL);
export interface Post {
id: string;
slug: string;
title: string;
description: string;
author: string;
category: string;
categoryColor: string;
date: string;
readTime: string;
imageUrl: string;
content?: string;
draft: boolean;
}
export async function getPosts(options?: {
page?: number;
perPage?: number;
category?: string;
search?: string;
}): Promise<{ posts: Post[]; total: number; page: number; totalPages: number }> {
const page = options?.page || 1;
const perPage = options?.perPage || 10;
const filter: string[] = ['draft = false'];
if (options?.category && options.category !== 'Все') {
filter.push(`category = "${options.category}"`);
}
if (options?.search) {
filter.push(`(title ~ "${options.search}" || description ~ "${options.search}")`);
}
const result = await pb.collection('posts').getList(page, perPage, {
filter: filter.join(' && '),
sort: '-date',
});
return {
posts: (result.items || []) as unknown as Post[],
total: result.totalItems || 0,
page: (result.pageInfo?.page || 1),
totalPages: result.totalPages || 1,
};
}
export async function getPostBySlug(slug: string): Promise<Post | null> {
const result = await pb.collection('posts').getList(1, 1, {
filter: `slug="${slug}" && draft = false`,
});
if (!result.items || result.totalItems === 0) {
return null;
}
return result.items[0] as unknown as Post;
}
export async function getAllCategories(): Promise<string[]> {
const result = await pb.collection('posts').getFullList({
filter: 'draft = false',
fields: 'category',
});
const categories = (result || []).map((post: any) => post.category).filter(Boolean);
return ['Все', ...new Set(categories)];
}