1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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;
/**
* Local map to store task pageId to its last status.
* { [pageId: string]: string }
*/
const taskPageIdToStatusMap = {};
/**
* Initialize local data store.
* Then poll for changes every 5 seconds (5000 milliseconds).
*/
setInitialTaskPageIdToStatusMap().then(() => {
setInterval(findAndSendEmailsForUpdatedTasks, 5000);
});
/**
* Get and set the initial data store with tasks currently in the database.
*/
async function setInitialTaskPageIdToStatusMap() {
const currentTasks = await getTasksFromNotionDatabase();
for (const { pageId, status } of currentTasks) {
taskPageIdToStatusMap[pageId] = status;
}
}
async function findAndSendEmailsForUpdatedTasks() {
// Get the tasks currently in the database.
console.log("\nFetching tasks from Notion DB...");
const currentTasks = await getTasksFromNotionDatabase();
// Return any tasks that have had their status updated.
const updatedTasks = findUpdatedTasks(currentTasks);
console.log(`Found ${updatedTasks.length} updated tasks.`);
// For each updated task, update taskPageIdToStatusMap and send an email notification.
for (const task of updatedTasks) {
taskPageIdToStatusMap[task.pageId] = task.status;
await sendUpdateEmailWithSendgrid(task);
}
}
/**
* Gets tasks from the database.
*/
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;
}
/**
* Extract status as string from property value
*/
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";
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023