import type {
BlockObjectResponse,
PageObjectResponse,
QueryDatabaseParameters,
} from "@notionhq/client/build/src/api-endpoints";
import { Client } from "@notionhq/client";
export const getClient = () => {
const config = useRuntimeConfig();
const token = config.public.token;
if (!token)
throw new Error(
"The NUXT_PUBLIC_NOTION_TOKEN environment variable is required",
);
return new Client({
auth: token,
fetch: async (url, options) => {
const corsOptions = {
...options,
headers: {
...options?.headers,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
};
const response = await fetch(url, corsOptions);
if (response.status === 429) {
const retryAfter = response.headers.get("Retry-After");
if (retryAfter) {
const retryAfterSeconds = Number.parseInt(retryAfter, 10);
await new Promise((resolve) =>
setTimeout(resolve, retryAfterSeconds),
);
return fetch(url, corsOptions);
}
}
return response;
},
});
};
export const fetchPages = async (language: string, status = "Live") => {
const config = useRuntimeConfig();
const notionClient = getClient();
const databaseId = config.public.databaseId;
if (!databaseId) {
throw new Error(
"The NUXT_PUBLIC_NOTION_DATABASE_ID environment variable is required.",
);
}
const args: QueryDatabaseParameters = {
database_id: databaseId,
};
console.log("Fetching pages with status", status);
if (status !== "All")
args.filter = {
property: "status",
status: {
equals: status,
},
and: [{ property: "language", select: { equals: language } }],
};
return await notionClient.databases.query(args);
};