-
Notifications
You must be signed in to change notification settings - Fork 548
/
index.ts
402 lines (360 loc) · 11.5 KB
/
index.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Find the official Notion API client @ https:// github.com/makenotion/notion-sdk-js/
// npm install @notionhq/client
import { Client } from "@notionhq/client"
import {
CreatePageParameters,
GetDatabaseResponse,
GetPagePropertyResponse,
} from "@notionhq/client/build/src/api-endpoints"
import * as _ from "lodash"
import { config } from "dotenv"
config()
import * as faker from "faker"
const notion = new Client({ auth: process.env["NOTION_KEY"] })
const startTime = new Date()
startTime.setSeconds(0, 0)
// Given the properties of a database, generate an object full of
// random data that can be used to generate new rows in our Notion database.
function makeFakePropertiesData(
properties: GetDatabaseResponse["properties"]
): Record<string, CreatePageParameters["properties"]> {
const propertyValues: Record<string, CreatePageParameters["properties"]> = {}
Object.entries(properties).forEach(([name, property]) => {
if (property.type === "date") {
propertyValues[name] = {
type: "date",
date: {
start: faker.date.past().toISOString(),
},
}
} else if (property.type === "multi_select") {
const multiSelectOption = _.sample(property.multi_select.options)
if (multiSelectOption) {
propertyValues[name] = {
type: "multi_select",
multi_select: [multiSelectOption],
}
}
} else if (property.type === "select") {
const selectOption = _.sample(property.select.options)
if (selectOption) {
propertyValues[name] = {
type: "select",
id: property.id,
select: selectOption,
}
}
} else if (property.type === "email") {
propertyValues[name] = {
type: "email",
id: property.id,
email: faker.internet.email(),
}
} else if (property.type === "checkbox") {
propertyValues[name] = {
type: "checkbox",
id: property.id,
checkbox: faker.datatype.boolean(),
}
} else if (property.type === "url") {
propertyValues[name] = {
type: "url",
id: property.id,
url: faker.internet.url(),
}
} else if (property.type === "number") {
propertyValues[name] = {
type: "number",
id: property.id,
number: faker.datatype.number(),
}
} else if (property.type === "title") {
propertyValues[name] = {
type: "title",
id: property.id,
title: [
{
type: "text",
text: { content: faker.lorem.words(3) },
},
],
}
} else if (property.type === "rich_text") {
propertyValues[name] = {
type: "rich_text",
id: property.id,
rich_text: [
{
type: "text",
text: { content: faker.name.firstName() },
},
],
}
} else if (property.type === "phone_number") {
propertyValues[name] = {
type: "phone_number",
id: property.id,
phone_number: faker.phone.phoneNumber(),
}
} else {
console.log("unimplemented property type: ", property.type)
}
})
return propertyValues
}
function assertUnreachable(_x: never): never {
throw new Error("Didn't expect to get here")
}
function userToString(userBase: { id: string; name?: string | null }) {
return `${userBase.id}: ${userBase.name || "Unknown Name"}`
}
function findRandomSelectColumnNameAndValue(
properties: GetDatabaseResponse["properties"]
): {
name: string
value: string | undefined
} {
const options = _.flatMap(Object.entries(properties), ([name, property]) => {
if (property.type === "select") {
return [
{ name, value: _.sample(property.select.options.map(o => o.name)) },
]
}
return []
})
if (options.length > 0) {
return _.sample(options) || { name: "", value: undefined }
}
return { name: "", value: undefined }
}
function extractPropertyItemValueToString(
property: Extract<GetPagePropertyResponse, { object: "property_item" }>
): string {
switch (property.type) {
case "checkbox":
return property.checkbox.toString()
case "created_by":
return userToString(property.created_by)
case "created_time":
return new Date(property.created_time).toISOString()
case "date":
return property.date ? new Date(property.date.start).toISOString() : ""
case "email":
return property.email ?? ""
case "url":
return property.url ?? ""
case "number":
return typeof property.number === "number"
? property.number.toString()
: ""
case "phone_number":
return property.phone_number ?? ""
case "select":
if (!property.select) {
return ""
}
return `${property.select.id} ${property.select.name}`
case "multi_select":
if (!property.multi_select) {
return ""
}
return property.multi_select
.map(select => `${select.id} ${select.name}`)
.join(", ")
case "people":
return userToString(property.people)
case "last_edited_by":
return userToString(property.last_edited_by)
case "last_edited_time":
return new Date(property.last_edited_time).toISOString()
case "title":
return property.title.plain_text
case "rich_text":
return property.rich_text.plain_text
case "files":
return property.files.map(file => file.name).join(", ")
case "formula":
if (property.formula.type === "string") {
return property.formula.string || "???"
} else if (property.formula.type === "number") {
return property.formula.number?.toString() || "???"
} else if (property.formula.type === "boolean") {
return property.formula.boolean?.toString() || "???"
} else if (property.formula.type === "date") {
return (
(property.formula.date?.start &&
new Date(property.formula.date.start).toISOString()) ||
"???"
)
} else {
return assertUnreachable(property.formula)
}
case "rollup":
if (property.rollup.type === "number") {
return property.rollup.number?.toString() || "???"
} else if (property.rollup.type === "date") {
return (
(property.rollup.date?.start &&
new Date(property.rollup.date?.start).toISOString()) ||
"???"
)
} else if (property.rollup.type === "array") {
return JSON.stringify(property.rollup.array)
} else if (
property.rollup.type === "incomplete" ||
property.rollup.type === "unsupported"
) {
return property.rollup.type
} else {
return assertUnreachable(property.rollup)
}
case "relation":
if (property.relation) {
return property.relation.id
}
return "???"
case "status":
return property.status?.name ?? ""
}
return assertUnreachable(property)
}
function extractValueToString(property: GetPagePropertyResponse): string {
if (property.object === "property_item") {
return extractPropertyItemValueToString(property)
} else if (property.object === "list") {
return property.results
.map(result => extractPropertyItemValueToString(result))
.join(", ")
} else {
return assertUnreachable(property)
}
}
async function exerciseWriting(
databaseId: string,
properties: GetDatabaseResponse["properties"]
) {
console.log("\n\n********* Exercising Writing *********\n\n")
const RowsToWrite = 10
// generate a bunch of fake pages with fake data
for (let i = 0; i < RowsToWrite; i++) {
const propertiesData = makeFakePropertiesData(properties)
const parameters: CreatePageParameters = {
parent: {
database_id: databaseId,
},
properties: propertiesData,
} as CreatePageParameters
await notion.pages.create(parameters)
}
console.log(`Wrote ${RowsToWrite} rows after ${startTime}`)
}
async function exerciseReading(
databaseId: string,
_properties: GetDatabaseResponse["properties"]
) {
console.log("\n\n********* Exercising Reading *********\n\n")
// and read back what we just did
const queryResponse = await notion.databases.query({
database_id: databaseId,
})
let numOldRows = 0
for (const page of queryResponse.results) {
if (!("url" in page)) {
// Skip partial page objects (these shouldn't be returned anyway.)
continue
}
const createdTime = new Date(page.created_time)
if (startTime > createdTime) {
numOldRows++
return
}
console.log(`New page: ${page.id}`)
for (const [name, property] of Object.entries(page.properties)) {
const propertyResponse = await notion.pages.properties.retrieve({
page_id: page.id,
property_id: property.id,
})
console.log(
` - ${name} ${property.id} - ${extractValueToString(propertyResponse)}`
)
}
}
console.log(
`Skipped printing ${numOldRows} rows that were written before ${startTime}`
)
}
async function exerciseFilters(
databaseId: string,
properties: GetDatabaseResponse["properties"]
) {
console.log("\n\n********* Exercising Filters *********\n\n")
// get a random select or multi-select column from the collection with a random value for it
const { name: selectColumnName, value: selectColumnValue } =
findRandomSelectColumnNameAndValue(properties)
if (!selectColumnName || !selectColumnValue) {
throw new Error("need a select column to run this part of the example")
}
console.log(`Looking for ${selectColumnName}=${selectColumnValue}`)
// Check we can search by name
const queryFilterSelectFilterTypeBased = {
property: selectColumnName,
select: { equals: selectColumnValue },
}
const matchingSelectResults = await notion.databases.query({
database_id: databaseId,
filter: queryFilterSelectFilterTypeBased,
})
console.log(
`had ${matchingSelectResults.results.length} matching rows for ${selectColumnName}=${selectColumnValue}`
)
// Let's do it again for text
const textColumn = _.sample(
Object.values(properties).filter(p => p.type === "rich_text")
)
if (!textColumn) {
throw new Error(
"Need a rich_text column for this part of the test, could not find one"
)
}
const textColumnId = decodeURIComponent(textColumn.id)
const letterToFind = faker.lorem.word(1)
console.log(
`\n\nLooking for text column with id "${textColumnId}" contains letter "${letterToFind}"`
)
const textFilter = {
property: textColumnId,
rich_text: { contains: letterToFind },
}
// Check we can search by id
const matchingTextResults = await notion.databases.query({
database_id: databaseId,
filter: textFilter,
})
console.log(
`Had ${matchingTextResults.results.length} matching rows in column with ID "${textColumnId}" containing letter "${letterToFind}"`
)
}
async function main() {
// Find the first database this bot has access to
const databases = await notion.search({
filter: {
property: "object",
value: "database",
},
})
if (databases.results.length === 0) {
throw new Error("This bot doesn't have access to any databases!")
}
const database = databases.results[0]
if (!database) {
throw new Error("This bot doesn't have access to any databases!")
}
// Get the database properties out of our database
const { properties } = await notion.databases.retrieve({
database_id: database.id,
})
await exerciseWriting(database.id, properties)
await exerciseReading(database.id, properties)
await exerciseFilters(database.id, properties)
}
main()