add categories
This commit is contained in:
87
src/lib/wpInfo.js
Normal file
87
src/lib/wpInfo.js
Normal file
@@ -0,0 +1,87 @@
|
||||
import { fetchGraphQL } from './graphql-client.js';
|
||||
|
||||
class WPInfo {
|
||||
constructor() {
|
||||
this.categories = null;
|
||||
}
|
||||
|
||||
// Запрос всех рубрик используя вашу библиотеку
|
||||
async fetchAllCategories() {
|
||||
const query = `
|
||||
query GetCategories($first: Int) {
|
||||
categories(first: $first) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
name
|
||||
color
|
||||
slug
|
||||
uri
|
||||
databaseId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
try {
|
||||
// Используем вашу существующую функцию fetchGraphQL
|
||||
const data = await fetchGraphQL(query, { first: 100 });
|
||||
|
||||
// Извлекаем node из каждого edge (как в getLatestPosts)
|
||||
if (data?.categories?.edges) {
|
||||
this.categories = data.categories.edges.map(edge => edge.node);
|
||||
} else if (data?.data?.categories?.edges) {
|
||||
this.categories = data.data.categories.edges.map(edge => edge.node);
|
||||
}
|
||||
|
||||
return this.categories;
|
||||
} catch (error) {
|
||||
console.error('Error fetching categories:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Получить рубрику по ID
|
||||
getCategoryById(id) {
|
||||
if (!this.categories) return null;
|
||||
return this.categories.find(cat =>
|
||||
cat.id === id ||
|
||||
cat.databaseId === parseInt(id)
|
||||
);
|
||||
}
|
||||
|
||||
// Получить рубрику по slug
|
||||
getCategoryBySlug(slug) {
|
||||
if (!this.categories) return null;
|
||||
return this.categories.find(cat => cat.slug === slug);
|
||||
}
|
||||
|
||||
// Получить все рубрики
|
||||
getAllCategories() {
|
||||
return this.categories || [];
|
||||
}
|
||||
|
||||
// Получить рубрики с фильтрацией
|
||||
getCategories(filterFn) {
|
||||
if (!this.categories) return [];
|
||||
return this.categories.filter(filterFn);
|
||||
}
|
||||
|
||||
// Проверить, загружены ли рубрики
|
||||
isLoaded() {
|
||||
return this.categories !== null;
|
||||
}
|
||||
|
||||
// Очистить кеш (если нужно обновить)
|
||||
clearCache() {
|
||||
this.categories = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Создаем и экспортируем единственный экземпляр
|
||||
export const wpInfo = new WPInfo();
|
||||
|
||||
wpInfo.fetchAllCategories().then(() => {
|
||||
console.log('✅ WPInfo: данные рубрик загружены в память и будут храниться постоянно');
|
||||
});
|
||||
Reference in New Issue
Block a user