74 lines
1.9 KiB
TypeScript
74 lines
1.9 KiB
TypeScript
|
|
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)];
|
|||
|
|
}
|