mosaicmap/lib/fetchers.ts
2025-08-17 20:28:13 +08:00

70 lines
1.7 KiB
TypeScript

import { gql, GraphQLClient } from "graphql-request";
import type { PageData } from "@/types/page";
import { getBaseUrl } from "./gr-client";
const PageQuery = gql/* GraphQL */ `
query PageQuery($slug: String!) {
pageBySlug(slug: $slug) {
id
title
description
}
}
`;
const BlockQuery = gql/* GraphQL */ `
query BlockQuery($pageId: String!) {
pageBlocks(pageId: $pageId) {
__typename
... on TextBlockType { id markdown }
... on ChartBlockType { id title series { x y } }
... on SettingsBlockType { id category editable }
... on HeroBlockType { id title subtitle backgroundImage ctaText ctaLink }
}
}
`;
export async function fetchPage(slug: string, jwt?: string): Promise<PageData | null> {
const client = new GraphQLClient(getBaseUrl());
if (jwt) {
client.setHeader('Authorization', `Bearer ${jwt}`);
}
try {
// 获取页面基本信息
const pageResponse: any = await client.request(PageQuery, { slug });
if (!pageResponse?.pageBySlug) {
throw new Error('Page not found');
}
// 获取页面块数据
const blocksResponse: any = await client.request(BlockQuery, {
pageId: pageResponse.pageBySlug.id
});
if (!blocksResponse?.pageBlocks) {
throw new Error('Failed to fetch page blocks');
}
// 合并数据
return {
...pageResponse.pageBySlug,
blocks: blocksResponse.pageBlocks,
};
} catch (error) {
console.error('Failed to fetch page:', error);
return null;
}
}
export async function getSiteConfigs() {
const baseUrl = process.env.GRAPHQL_BACKEND_URL || 'http://localhost:3000';
const siteConfigs = await fetch(`${baseUrl}/api/site`);
const data = await siteConfigs.json();
return data;
}