mirror of
https://git.rdcenter.ru/RDCenter/skb-kit.git
synced 2026-12-05 02:49:45 +00:00
перенес структуру Севы со своими правками
This commit is contained in:
1 parent
3a1cac0dfe
commit
808d97eb4b
331 files changed
+12260
-19950
No files matched your search
@@ -0,0 +1,11 @@
|
||||
import { skbEndpoint } from "@/shared/api/wp-client";
|
||||
|
||||
export const submitContactForm = async (formData: FormData) => {
|
||||
const response = await fetch(`${skbEndpoint}skbkit/v1/sendcontactform`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Form submission failed");
|
||||
return response;
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { submitContactForm } from "../api/post";
|
||||
|
||||
export const useContactForm = () => {
|
||||
return useMutation({
|
||||
mutationFn: submitContactForm,
|
||||
onSuccess: () => console.log("Форма успешно отправлена"),
|
||||
onError: (error: Error) => console.error("Ошибка отправки:", error),
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
export { useMedia } from "./media/hooks/useMedia";
|
||||
export { usePostById } from "./posts/hooks/usePostById";
|
||||
export { useNews } from "./news/hooks/useNews";
|
||||
export { useContactForm } from "./contact/hooks/useContactForm";
|
||||
@@ -0,0 +1,47 @@
|
||||
import { wp } from "@/shared/api/wp-client";
|
||||
import { WPv2 } from "@/shared/types/app";
|
||||
|
||||
export interface MediaItem {
|
||||
id: number;
|
||||
src: string;
|
||||
category: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Функция для получения всех медиафайлов с учетом пагинации
|
||||
*/
|
||||
export const fetchMedia = async (): Promise<MediaItem[]> => {
|
||||
let page = 1;
|
||||
let allMedia: MediaItem[] = [];
|
||||
let hasMore = true;
|
||||
|
||||
while (hasMore) {
|
||||
try {
|
||||
// Запрашиваем медиа с указанной страницы
|
||||
const media = (await wp.media().page(page)) as WPv2.Media[];
|
||||
|
||||
// Если медиа нет, завершаем цикл
|
||||
if (!media.length) {
|
||||
hasMore = false;
|
||||
break;
|
||||
}
|
||||
|
||||
// Преобразуем данные и добавляем в общий массив
|
||||
const transformedMedia = media.map(({ id, source_url, alt_text }) => {
|
||||
const [category = "uncategorized", name = "unknown"] =
|
||||
alt_text?.split("_") || [];
|
||||
return { id, src: source_url, category, name };
|
||||
});
|
||||
|
||||
allMedia = [...allMedia, ...transformedMedia];
|
||||
page++; // Переходим на следующую страницу
|
||||
} catch (error) {
|
||||
// Если произошла ошибка (например, страница не найдена), завершаем цикл
|
||||
hasMore = false;
|
||||
console.error("Ошибка при загрузке медиа:", error);
|
||||
}
|
||||
}
|
||||
|
||||
return allMedia;
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { fetchMedia } from "@/modules/media/api/get";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
export const useMedia = () => {
|
||||
return useQuery({
|
||||
queryKey: ["media"],
|
||||
queryFn: fetchMedia,
|
||||
staleTime: 1000 * 60 * 5, // 5 минут
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { skbEndpoint } from "@/shared/api/wp-client";
|
||||
import { SKBKit } from "@/shared/types/app";
|
||||
|
||||
export const fetchNews = async <T = SKBKit.News[]>(params?: {
|
||||
count?: number;
|
||||
offset?: number;
|
||||
}): Promise<SKBKit.ApiResponse<T>> => {
|
||||
const url = new URL(`${skbEndpoint}skbkit/v1/getnews`);
|
||||
|
||||
if (params) {
|
||||
if (params.count) url.searchParams.set("count", params.count.toString());
|
||||
if (params.offset) url.searchParams.set("offset", params.offset.toString());
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString());
|
||||
const data: T = await response.json();
|
||||
|
||||
return {
|
||||
data,
|
||||
headers: {
|
||||
"x-wp-total": response.headers.get("x-wp-total") || "0",
|
||||
"x-wp-totalpages": response.headers.get("x-wp-totalpages") || "0",
|
||||
},
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
import { fetchNews } from "@/modules/news/api/get";
|
||||
import { keepPreviousData, useQuery } from "@tanstack/react-query";
|
||||
|
||||
export const useNews = (params?: { count?: number; offset?: number }) => {
|
||||
return useQuery({
|
||||
queryKey: ["news", params],
|
||||
queryFn: () => fetchNews(params),
|
||||
select: (news) => news.data,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { skbEndpoint } from "@/shared/api/wp-client";
|
||||
import { SKBKit } from "@/shared/types/app";
|
||||
export const fetchNewsById = async (id: string): Promise<SKBKit.News> => {
|
||||
const response = await fetch(`${skbEndpoint}skbkit/v1/getnewsbyid?id=${id}`);
|
||||
if (!response.ok) throw new Error("Ошибка при загрузке новости");
|
||||
const data = await response.json();
|
||||
return data;
|
||||
};
|
||||
|
||||
export const useNewsById = (id: string) => {
|
||||
return useQuery<SKBKit.News>({
|
||||
queryKey: ["news", id],
|
||||
queryFn: () => fetchNewsById(id),
|
||||
enabled: !!id,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
// posts/api/get.ts
|
||||
import { wp } from "@/shared/api/wp-client";
|
||||
import { parseContent } from "@/shared/api/parseContent";
|
||||
import { fetchMedia } from "@/modules/media/api/get";
|
||||
import { App, WPv2 } from "@/shared/types/app";
|
||||
import Parse from "html-react-parser";
|
||||
export const fetchPosts = async (): Promise<App.PostsResult> => {
|
||||
const [posts, categories, tags, mediaLibrary] = await Promise.all([
|
||||
wp.posts().param("per_page", 100).get() as Promise<WPv2.Post[]>,
|
||||
wp.categories().get() as Promise<WPv2.Category[]>,
|
||||
wp.tags().get() as Promise<WPv2.Tag[]>,
|
||||
fetchMedia(),
|
||||
]);
|
||||
|
||||
const categoryMap = new Map<number, string>(
|
||||
categories.map((c) => [c.id, c.name])
|
||||
);
|
||||
const tagMap = new Map<number, string>(tags.map((t) => [t.id, t.name]));
|
||||
|
||||
const result: App.PostsResult = {
|
||||
projects: {},
|
||||
labs: {},
|
||||
other: [],
|
||||
};
|
||||
|
||||
for (const post of posts) {
|
||||
const image = mediaLibrary.find((item) => item.id === post.featured_media);
|
||||
const postCategories = post.categories.map(
|
||||
(id) => categoryMap.get(id) || ""
|
||||
);
|
||||
|
||||
const newPost: App.ProjectPost = {
|
||||
id: post.id,
|
||||
title: post.title.rendered,
|
||||
content: parseContent(post.content.rendered),
|
||||
lab: "",
|
||||
preview: image?.src || null,
|
||||
categories: postCategories,
|
||||
tag: post.tags.map((id) => tagMap.get(id) || "")[0] || "",
|
||||
};
|
||||
|
||||
if (postCategories.includes("projects")) {
|
||||
newPost.lab = postCategories.filter((c) => c !== "projects")[0] || "";
|
||||
result.projects[post.id] = newPost;
|
||||
} else if (postCategories.includes("labs")) {
|
||||
//@ts-ignore
|
||||
const excerptElement = Parse(post.excerpt.rendered)[0];
|
||||
newPost.previewText = (excerptElement as any)?.props?.children || "";
|
||||
result.labs[post.id] = newPost as App.LabPost;
|
||||
} else {
|
||||
result.other.push(newPost);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
// posts/api/useProjectById.ts
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { wp } from "@/shared/api/wp-client";
|
||||
import { parseContent } from "@/shared/api/parseContent";
|
||||
import { App, WPv2 } from "@/shared/types/app";
|
||||
|
||||
export const usePostById = (id: number) => {
|
||||
return useQuery<App.ProjectPost>({
|
||||
queryKey: ["project", id],
|
||||
queryFn: async () => {
|
||||
const [post, categories] = await Promise.all([
|
||||
wp.posts().id(id).get() as Promise<WPv2.Post>,
|
||||
wp.categories().param("post", id).get() as Promise<WPv2.Category[]>,
|
||||
]);
|
||||
|
||||
const categoryNames = categories.map((c) => c.name);
|
||||
|
||||
return {
|
||||
id: post.id,
|
||||
title: post.title.rendered,
|
||||
content: parseContent(post.content.rendered),
|
||||
lab: categoryNames.find((c) => c !== "projects") || "",
|
||||
preview: post.featured_media?.toString() || null,
|
||||
categories: categoryNames,
|
||||
tag: "",
|
||||
};
|
||||
},
|
||||
enabled: !!id,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
// posts/api/usePosts.ts
|
||||
import { fetchPosts } from "@/modules/posts/api/get";
|
||||
import { App } from "@/shared/types/app";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
export const usePosts = () => {
|
||||
return useQuery<App.PostsResult>({
|
||||
queryKey: ["posts"],
|
||||
queryFn: fetchPosts,
|
||||
staleTime: 1000 * 60 * 5,
|
||||
});
|
||||
};
|
||||
Reference in new issue
Block a user