添加推荐问题修改接口

This commit is contained in:
fengxiangdebaozi committed 2026-05-14 11:07:28 +08:00
1 parent 62292500ba
commit 2f2ba44c7c
13 files changed
+481 -126

No files matched your search

@@ -0,0 +1,66 @@
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import type {
CreateQuestionRequest,
RecommendedQuestion,
UpdateQuestionRequest,
} from "./index";
const BASE = () => `${getBackendBaseURL()}/api/recommended-questions`;
export async function listRecommendedQuestions(): Promise<RecommendedQuestion[]> {
const res = await apiFetch(BASE());
if (!res.ok) throw new Error(`Failed to load questions: ${res.statusText}`);
const data = (await res.json()) as { questions: RecommendedQuestion[] };
return data.questions;
}
export async function createRecommendedQuestion(
body: CreateQuestionRequest,
): Promise<RecommendedQuestion> {
const res = await apiFetch(BASE(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to create question: ${res.statusText}`);
}
return res.json() as Promise<RecommendedQuestion>;
}
export async function updateRecommendedQuestion(
id: string,
body: UpdateQuestionRequest,
): Promise<RecommendedQuestion> {
const res = await apiFetch(`${BASE()}/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to update question: ${res.statusText}`);
}
return res.json() as Promise<RecommendedQuestion>;
}
export async function deleteRecommendedQuestion(id: string): Promise<void> {
const res = await apiFetch(`${BASE()}/${id}`, { method: "DELETE" });
if (!res.ok) throw new Error(`Failed to delete question: ${res.statusText}`);
}
export async function reorderRecommendedQuestions(
ids: string[],
): Promise<RecommendedQuestion[]> {
const res = await apiFetch(`${getBackendBaseURL()}/api/recommended-questions-reorder`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids }),
});
if (!res.ok) throw new Error(`Failed to reorder questions: ${res.statusText}`);
const data = (await res.json()) as { questions: RecommendedQuestion[] };
return data.questions;
}
@@ -1,58 +1,53 @@
import { useCallback, useSyncExternalStore } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
DEFAULT_QUESTIONS,
getRecommendedQuestions,
saveRecommendedQuestions,
type RecommendedQuestion,
} from "./index";
createRecommendedQuestion,
deleteRecommendedQuestion,
listRecommendedQuestions,
reorderRecommendedQuestions,
updateRecommendedQuestion,
} from "./api";
import type { CreateQuestionRequest, UpdateQuestionRequest } from "./index";
type Listener = () => void;
const QK = ["recommended-questions"] as const;
const listeners = new Set<Listener>();
let cached: RecommendedQuestion[] | null = null;
function getSnapshot(): RecommendedQuestion[] {
if (cached === null) {
cached = getRecommendedQuestions();
}
return cached;
export function useRecommendedQuestions() {
const { data, isLoading, error } = useQuery({
queryKey: QK,
queryFn: listRecommendedQuestions,
});
return { questions: data ?? [], isLoading, error };
}
function getServerSnapshot(): RecommendedQuestion[] {
return DEFAULT_QUESTIONS;
export function useCreateRecommendedQuestion() {
const qc = useQueryClient();
return useMutation({
mutationFn: (body: CreateQuestionRequest) => createRecommendedQuestion(body),
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
});
}
function subscribe(listener: Listener): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
export function useUpdateRecommendedQuestion() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, body }: { id: string; body: UpdateQuestionRequest }) =>
updateRecommendedQuestion(id, body),
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
});
}
function emitChange() {
for (const l of listeners) l();
export function useDeleteRecommendedQuestion() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => deleteRecommendedQuestion(id),
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
});
}
export function updateRecommendedQuestions(
questions: RecommendedQuestion[],
): void {
cached = questions;
saveRecommendedQuestions(questions);
emitChange();
}
export function useRecommendedQuestions(): [
RecommendedQuestion[],
(questions: RecommendedQuestion[]) => void,
] {
const questions = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
const save = useCallback((qs: RecommendedQuestion[]) => {
updateRecommendedQuestions(qs);
}, []);
return [questions, save];
export function useReorderRecommendedQuestions() {
const qc = useQueryClient();
return useMutation({
mutationFn: (ids: string[]) => reorderRecommendedQuestions(ids),
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
});
}
@@ -2,56 +2,19 @@ export interface RecommendedQuestion {
id: string;
title: string;
content: string;
sort_order: number;
created_at?: string;
updated_at?: string;
}
const STORAGE_KEY = "deerflow.recommended-questions";
export const DEFAULT_QUESTIONS: RecommendedQuestion[] = [
{
id: "default-1",
title: "市场分析报告",
content:
"请帮我写一份关于当前 AI 市场的详细分析报告,包括市场规模、主要玩家和发展趋势。",
},
{
id: "default-2",
title: "制定学习计划",
content:
"请帮我制定一个为期 3 个月的 Python 编程学习计划,从基础到进阶,每周安排具体任务。",
},
{
id: "default-3",
title: "代码审查建议",
content:
"请帮我审查代码,找出潜在的问题、性能瓶颈以及改进建议,并给出修改示例。",
},
{
id: "default-4",
title: "数据分析方案",
content:
"请帮我设计一个用于分析用户行为数据的方案,包括数据收集、处理和可视化策略。",
},
{
id: "default-5",
title: "文章润色优化",
content: "请帮我润色以下文章,使其更加流畅、专业,并保持原意不变。",
},
];
export function getRecommendedQuestions(): RecommendedQuestion[] {
if (typeof window === "undefined") return DEFAULT_QUESTIONS;
const json = localStorage.getItem(STORAGE_KEY);
if (!json) return DEFAULT_QUESTIONS;
try {
const parsed = JSON.parse(json) as RecommendedQuestion[];
if (Array.isArray(parsed) && parsed.length > 0) return parsed;
} catch {}
return DEFAULT_QUESTIONS;
export interface CreateQuestionRequest {
title: string;
content: string;
sort_order?: number;
}
export function saveRecommendedQuestions(
questions: RecommendedQuestion[],
): void {
if (typeof window === "undefined") return;
localStorage.setItem(STORAGE_KEY, JSON.stringify(questions));
export interface UpdateQuestionRequest {
title?: string;
content?: string;
sort_order?: number;
}