// frontend/src/lib/api.ts
import type { InferResponse } from "@xano/sdk";
import type { createPost, getPost } from "../../../xano/api/blog.js";
import { ROUTES, routePath, type RouteInputs } from "../../../xano/routes.gen.js";
declare global {
interface Window {
XANO_HOST?: string;
}
}
// The backend URL: injected by a deploy as window.XANO_HOST, else VITE_XANO_HOST in dev.
export const XANO_HOST: string =
(typeof window !== "undefined" && window.XANO_HOST) ||
import.meta.env.VITE_XANO_HOST ||
"";
export type NewPost = RouteInputs["POST posts"];
export type Post = InferResponse<typeof createPost>;
export type MaybePost = InferResponse<typeof getPost>;
export async function fetchPost(id: number): Promise<MaybePost> {
const res = await fetch(XANO_HOST + routePath("GET posts/{id}", { id }), {
method: ROUTES["GET posts/{id}"].verb,
});
if (!res.ok) throw new Error(await res.text());
return res.json();
}
export async function createPostRequest(body: NewPost, token: string): Promise<Post> {
const res = await fetch(XANO_HOST + routePath("POST posts"), {
method: ROUTES["POST posts"].verb,
headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(await res.text());
return res.json();
}