Back to packages list

Vals using @notionhq/client

Description from the NPM package:
A simple and easy to use client for the Notion API
Runs every 1461 days
Fork
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
import process from "node:process";
import { Client } from "npm:@notionhq/client";
import { fetch } from "npm:cross-fetch";
export default async function(interval: Interval) {
const NOTION_API_KEY = process.env.NOTION_API_KEY;
const PAPERPILE_DB_ID = "DB_ID_GOES_HERE";
if (!NOTION_API_KEY || !PAPERPILE_DB_ID) {
throw new Error("Please fill in your API key and database ID");
}
let dont_update = [];
const notion = new Client({ auth: NOTION_API_KEY });
const databaseId = PAPERPILE_DB_ID;
const queryResponse = await notion.databases.query({
database_id: databaseId,
page_size: 100,
filter: {
or: [
{
property: "Name",
rich_text: {
contains: ";",
},
},
],
},
});
const relevant_results = queryResponse.results.filter(
(i) => !dont_update.includes(i.id),
);
console.log(
`Checked database, found ${relevant_results.length} items to update.`,
);
const all_updated = [];
for (var i of relevant_results) {
let semscholar_query = i.properties.Name.title[0]
.plain_text.replace(
/[^\w\s]/gi,
" ",
); /*+ " " + i.properties["Author(s)"].multi_select.map(x => x.name).join(", ")*/
console.log(semscholar_query);
let fields = `url,title,abstract,authors,year,externalIds`;
const j = await fetch(
`https://api.semanticscholar.org/graph/v1/paper/search?query=${
encodeURIComponent(
semscholar_query,
)
}&limit=1&fields=${
encodeURIComponent(
fields,
)
}`,
).then((r) => r.json()).catch(function() {
console.log("Promise Rejected");
});
if (!(j.total > 0)) {
console.log("No results found for " + semscholar_query);
continue;
}
const paper = j.data[0];
// get bibtex
let all_external_ids = paper.externalIds;
// console.log(paper)
// console.log(all_external_ids)
let doi_to_add = null;
let bibtext_to_add = null;
if (paper.externalIds.DOI) {
doi_to_add = paper.externalIds.DOI;
}
else if (paper.externalIds.PubMed) {
doi_to_add = paper.externalIds.PubMed;
}
else if (paper.externalIds.PubMedCentral) {
doi_to_add = paper.externalIds.PubMedCentral;
}
else if (paper.externalIds.ArXiv) {
doi_to_add = "arxiv." + paper.externalIds.ArXiv;
}
if (doi_to_add) {
// const bib = await fetch('https://api.paperpile.com/api/public/convert', {
// method: 'POST',
// headers: {
// 'Accept': 'application/json, text/plain, */*',
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({fromIds: true, input: doi_to_add.replace("arxiv.",""), targetFormat: "Bibtex"})
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";
1
Next