Some common variables for all functions
const NOTION_API_KEY = process.env.NOTION_API_KEY;
const headers = {
Accept: "application/json",
"Notion-Version": "2021-08-16",
"Content-Type": "application/json",
};
type NotionPageProperties = {
[key: string]: string | boolean | number;
};
type NotionAPIResponse = {
body: { [key: string]: any };
status: number;
};
async function getPageByID(pageID: string): Promise<NotionAPIResponse> {
const response = await fetch(`https://api.notion.com/v1/pages/${pageID}`, {
method: "GET",
headers: { ...headers, Authorization: `Bearer ${NOTION_API_KEY}` },
});
const body = await response.json();
return { body, status: response.status };
}
async function updatePageByID(
pageID: string,
properties: NotionPageProperties
): Promise<NotionAPIResponse> {
const response = await fetch(`https://api.notion.com/v1/pages/${pageID}`, {
method: "PATCH",
headers: { ...headers, Authorization: `Bearer ${NOTION_API_KEY}` },
body: JSON.stringify({
properties: properties,
}),
});
const body = await response.json();
return { body, status: response.status };
}
async function createPageInParentID(
parentID: string,
properties: NotionPageProperties
): Promise<NotionAPIResponse> {
const response = await fetch("https://api.notion.com/v1/pages", {
method: "POST",
headers: { ...headers, Authorization: `Bearer ${NOTION_API_KEY}` },
body: JSON.stringify({
parent: { database_id: parentID },
properties: properties,
}),
});
const body = await response.json();
return { body, status: response.status };
}
async function duplicatePageByID(
pageID: string,
properties: NotionPageProperties
): Promise<NotionAPIResponse> {
const page = await getPageByID(pageID);
const newPage = await createPageInParentID(page["parent"], {
...page.body.properties,
...properties,
});
return { body: newPage.body, status: newPage.status };
}
async function archivePageByID(pageID: string): Promise<NotionAPIResponse> {
const response = await fetch(`https://api.notion.com/v1/pages/${pageID}`, {
method: "PATCH",
headers: { ...headers, Authorization: `Bearer ${NOTION_API_KEY}` },
body: JSON.stringify({
properties: { archived: true },
}),
});
const body = await response.json();
return { body, status: response.status };
}