export const setDatabaseFieldValue = async () => {
const { Client } = await import("npm:@notionhq/client");
const { config } = await import("npm:dotenv");
const { default: SendGrid } = await import("npm:@sendgrid/mail");
const { PropertyItemObjectResponse } = await import(
"npm:../../build/src/api-endpoints"
);
config();
SendGrid.setApiKey(process.env.SENDGRID_KEY);
const notion = new Client({ auth: process.env.NOTION_KEY });
const databaseId = process.env.NOTION_DATABASE_ID;
const taskPageIdToStatusMap = {};
setInitialTaskPageIdToStatusMap().then(() => {
setInterval(findAndSendEmailsForUpdatedTasks, 5000);
});
async function setInitialTaskPageIdToStatusMap() {
const currentTasks = await getTasksFromNotionDatabase();
for (const { pageId, status } of currentTasks) {
taskPageIdToStatusMap[pageId] = status;
}
}
async function findAndSendEmailsForUpdatedTasks() {
console.log("\nFetching tasks from Notion DB...");
const currentTasks = await getTasksFromNotionDatabase();
const updatedTasks = findUpdatedTasks(currentTasks);
console.log(`Found ${updatedTasks.length} updated tasks.`);
for (const task of updatedTasks) {
taskPageIdToStatusMap[task.pageId] = task.status;
await sendUpdateEmailWithSendgrid(task);
}
}
async function getTasksFromNotionDatabase(): Promise<
Array<{
pageId: string;
status: string;
title: string;
}>
> {
const pages = [];
let cursor = undefined;
const shouldContinue = true;
while (shouldContinue) {
const { results, next_cursor } = await notion.databases.query({
database_id: databaseId,
start_cursor: cursor,
});
pages.push(...results);
if (!next_cursor) {
break;
}
cursor = next_cursor;
}
console.log(`${pages.length} pages successfully fetched.`);
const tasks = [];
for (const page of pages) {
const pageId = page.id;
const statusPropertyId = page.properties["Status"].id;
const statusPropertyItem = await getPropertyValue({
pageId,
propertyId: statusPropertyId,
});
const status = getStatusPropertyValue(statusPropertyItem);
const titlePropertyId = page.properties["Name"].id;
const titlePropertyItems = await getPropertyValue({
pageId,
propertyId: titlePropertyId,
});
const title = getTitlePropertyValue(titlePropertyItems);
tasks.push({ pageId, status, title });
}
return tasks;
}
function getStatusPropertyValue(
property: PropertyItemObjectResponse | Array<PropertyItemObjectResponse>
): string {
if (Array.isArray(property)) {
if (property?.[0]?.type === "select") {
return property[0].select.name;
} else {
return "No Status";