@haustle/notion-orm 0.0.41 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,14 +10,20 @@
10
10
  A library to simplify interacting with [Notion](https://notion.so/product) databases/tables via Notion API
11
11
 
12
12
  ## Disclaimer
13
+ ### Available Database Features
14
+ - Adding
15
+ - Querying
13
16
 
14
- This library currently only supports databases that use the following column types
15
-
17
+ ### Supported Column Types
16
18
  - Multiselect
17
- - Text
18
19
  - Select
20
+ - Status
21
+ - Date
22
+ - Text
19
23
  - Url
20
24
  - Checkbox
25
+ - Email
26
+ - Phone Number
21
27
 
22
28
  # Install and Setup
23
29
 
@@ -38,8 +44,8 @@ The only requirement is a Notion Developer API Key ([here](https://developers.no
38
44
  const NotionConfig = {
39
45
  auth: process.env.NOTION_KEY,
40
46
  databaseIds: [
41
- "a52239e4839d4a3a8f4875376cfbfb02",
42
- "5f4bf76a1e3f48d684d2506ea2690d64"
47
+ "a52239e4839d4a3a8f4875376cfbfb02",
48
+ "5f4bf76a1e3f48d684d2506ea2690d64"
43
49
  ],
44
50
  };
45
51
 
@@ -72,8 +78,8 @@ Page title is required when adding
72
78
 
73
79
  ```tsx
74
80
  notion.books.add({
75
- name: "Catcher in the Rye",
76
- rating: "⭐️⭐️⭐️⭐️⭐️"
81
+ name: "Catcher in the Rye",
82
+ rating: "⭐️⭐️⭐️⭐️⭐️"
77
83
  })
78
84
  ```
79
85
 
@@ -83,11 +89,11 @@ notion.books.add({
83
89
 
84
90
  ```tsx
85
91
  notion.books.query({
86
- filter: {
87
- genre: {
88
- contains: "Sci-Fi"
89
- }
90
- }
92
+ filter: {
93
+ genre: {
94
+ contains: "Sci-Fi"
95
+ }
96
+ }
91
97
  })
92
98
  ```
93
99
 
@@ -95,21 +101,21 @@ notion.books.query({
95
101
 
96
102
  ```tsx
97
103
  await notion.books.query({
98
- filter: {
99
- or: [
100
- {
101
- genre: {
102
- contains: "Sci-Fi",
103
- },
104
- },
105
- {
106
- genre: {
107
- contains: "Biography",
108
- },
109
- },
110
- ],
111
- },
112
- });
104
+ filter: {
105
+ or: [
106
+ {
107
+ genre: {
108
+ contains: "Sci-Fi",
109
+ },
110
+ },
111
+ {
112
+ genre: {
113
+ contains: "Biography",
114
+ },
115
+ },
116
+ ],
117
+ },
118
+ });
113
119
  ```
114
120
 
115
121
  ## What is Object Relational Map (ORM)
package/build/src/cli.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@haustle/notion-orm",
3
- "version": "0.0.41",
3
+ "version": "0.0.42",
4
4
  "description": "tool to bring notion databases schemas/types to typescript",
5
5
  "main": "build/databases/index.js",
6
6
  "bin": {
@@ -20,5 +20,13 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "@notionhq/client": "^2.2.2"
23
- }
23
+ },
24
+
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/Haustle/notion-orm"
28
+ },
29
+ "homepage": "https://github.com/Haustle/notion-orm#readme",
30
+ "keywords": ["notion orm", "typescript", "notion typesafety", "notion auto-complete", "notion databases", "notion-tables"]
31
+
24
32
  }
@@ -0,0 +1,118 @@
1
+ import { SupportedNotionColumnTypes } from "./queryTypes";
2
+
3
+ export function getCall(args: {
4
+ type: SupportedNotionColumnTypes;
5
+ value: string | number | boolean;
6
+ }) {
7
+ const { type, value } = args;
8
+ if (type === "select" && typeof value === "string") {
9
+ return selectCall({ value });
10
+ } else if (type === "multi_select" && Array.isArray(value)) {
11
+ return multiSelectCall({ value });
12
+ } else if (type === "status" && typeof value === "string") {
13
+ return statusCall({ option: value });
14
+ } else if (type === "number" && typeof value === "number") {
15
+ return numberCall({ value });
16
+ } else if (type === "email" && typeof value === "string") {
17
+ return emailCall({ value });
18
+ } else if (type === "date" && typeof value === "object") {
19
+ return dateCall({ value });
20
+ } else if (type === "phone_number" && typeof value === "string") {
21
+ return phoneNumberCall({ value });
22
+ } else if (type === "url" && typeof value === "string") {
23
+ return urlCall({ url: value });
24
+ } else if (type === "checkbox" && typeof value === "boolean") {
25
+ return checkboxCall({ checked: value });
26
+ } else if (type === "title" && typeof value === "string") {
27
+ return titleCall({ title: value });
28
+ } else if (type === "rich_text" && typeof value === "string") {
29
+ return textCall({ text: value });
30
+ } else {
31
+ console.error(
32
+ `'[@haustle/notion-orm] ${type}' column type currently not supported`
33
+ );
34
+ }
35
+ }
36
+
37
+ /*
38
+ ======================================================
39
+ GENERATE OBJECT BASED ON TYPE
40
+ ======================================================
41
+ */
42
+
43
+ const selectCall = (args: { value: string }) => {
44
+ const { value } = args;
45
+ const select = {
46
+ name: value,
47
+ };
48
+ return { select };
49
+ };
50
+
51
+ const dateCall = (args: { value: { start: string; end?: string } }) => {
52
+ const { value } = args;
53
+ return { date: value };
54
+ };
55
+ const phoneNumberCall = (args: { value: string }) => {
56
+ const { value } = args;
57
+ return { phone_number: value };
58
+ };
59
+
60
+ const statusCall = (args: { option: string }) => {
61
+ const { option } = args;
62
+ const status = {
63
+ name: option,
64
+ };
65
+ return { status };
66
+ };
67
+
68
+ const multiSelectCall = (args: { value: Array<string> }) => {
69
+ const { value } = args;
70
+ const multi_select = value.map((option) => ({ name: option }));
71
+ return { multi_select };
72
+ };
73
+
74
+ const textCall = (args: { text: string }) => {
75
+ const { text } = args;
76
+ const rich_text = [
77
+ {
78
+ text: {
79
+ content: text,
80
+ },
81
+ },
82
+ ];
83
+
84
+ return { rich_text };
85
+ };
86
+
87
+ const titleCall = (args: { title: string }) => {
88
+ const { title } = args;
89
+ const titleObject = [
90
+ {
91
+ text: {
92
+ content: title,
93
+ },
94
+ },
95
+ ];
96
+
97
+ return { title: titleObject };
98
+ };
99
+
100
+ const numberCall = (args: { value: number }) => {
101
+ const { value: number } = args;
102
+ return { number };
103
+ };
104
+
105
+ const urlCall = (args: { url: string }) => {
106
+ const { url } = args;
107
+ return { url };
108
+ };
109
+
110
+ const checkboxCall = (args: { checked: boolean }) => {
111
+ const { checked: checkbox } = args;
112
+ return { checkbox };
113
+ };
114
+
115
+ const emailCall = (args: { value: string }) => {
116
+ const { value } = args;
117
+ return { email: value };
118
+ };
@@ -0,0 +1,140 @@
1
+ import {
2
+ CreatePageParameters,
3
+ QueryDatabaseParameters,
4
+ } from "@notionhq/client/build/src/api-endpoints";
5
+ import { Client } from "@notionhq/client";
6
+ import { getCall } from "./BuildCall";
7
+ import path from "path";
8
+ import { NotionConfigType } from "./index";
9
+ import {
10
+ apiFilterType,
11
+ apiSingleFilter,
12
+ CompoundFilters,
13
+ Query,
14
+ QueryFilter,
15
+ SingleFilter,
16
+ SupportedNotionColumnTypes,
17
+ } from "./queryTypes";
18
+
19
+ export type propNameToColumnNameType = Record<
20
+ string,
21
+ { columnName: string; type: SupportedNotionColumnTypes }
22
+ >;
23
+
24
+ // Import auth key from config file
25
+ const { auth }: NotionConfigType = require(path.join(
26
+ process.cwd(),
27
+ "notion.config"
28
+ ));
29
+
30
+ export class DatabaseActions<
31
+ DatabaseSchemaType extends Record<string, any>,
32
+ ColumnNameToColumnType extends Record<
33
+ keyof DatabaseSchemaType,
34
+ SupportedNotionColumnTypes
35
+ >
36
+ > {
37
+ private NotionClient: Client = new Client({
38
+ auth,
39
+ });
40
+ private databaseId: string;
41
+ private propNameToColumnName: propNameToColumnNameType;
42
+ private columnNames: string[];
43
+
44
+ constructor(
45
+ datbaseId: string,
46
+ propNameToColumnName: propNameToColumnNameType
47
+ ) {
48
+ this.databaseId = datbaseId;
49
+ this.propNameToColumnName = propNameToColumnName;
50
+ this.columnNames = Object.keys(propNameToColumnName);
51
+ }
52
+
53
+ // Add page to a database
54
+ async add(pageObject: DatabaseSchemaType) {
55
+ const callBody: CreatePageParameters = {
56
+ parent: {
57
+ database_id: this.databaseId,
58
+ },
59
+ properties: {},
60
+ };
61
+
62
+ const columnTypePropNames = Object.keys(pageObject);
63
+ columnTypePropNames.forEach((propName) => {
64
+ const { type, columnName } = this.propNameToColumnName[propName];
65
+ const columnObject = getCall({
66
+ type,
67
+ value: pageObject[propName],
68
+ });
69
+
70
+ callBody.properties[columnName] = columnObject!;
71
+ });
72
+
73
+ // console.log(JSON.stringify(callBody, null, 4));
74
+ await this.NotionClient.pages.create(callBody);
75
+ }
76
+
77
+ // Look for page inside the database
78
+ async query(query: Query<DatabaseSchemaType, ColumnNameToColumnType>) {
79
+ const queryCall: QueryDatabaseParameters = {
80
+ database_id: this.databaseId,
81
+ };
82
+
83
+ const filters = query.filter
84
+ ? this.recursivelyBuildFilter(query.filter)
85
+ : undefined;
86
+ if (filters) {
87
+ // @ts-ignore errors vs notion api types
88
+ queryCall["filter"] = filters;
89
+ }
90
+
91
+ console.log(JSON.stringify(queryCall, null, 4));
92
+
93
+ const sort = query.sort;
94
+
95
+ const apiQuery = await this.NotionClient.databases.query(queryCall);
96
+ console.log(apiQuery);
97
+ }
98
+
99
+ private recursivelyBuildFilter(
100
+ queryFilter: QueryFilter<DatabaseSchemaType, ColumnNameToColumnType>
101
+ ): apiFilterType {
102
+ // Need to loop because we don't kno
103
+ for (const prop in queryFilter) {
104
+ // if the filter is "and" || "or" we need to recursively
105
+ if (prop === "and" || prop === "or") {
106
+ const compoundFilters: QueryFilter<
107
+ DatabaseSchemaType,
108
+ ColumnNameToColumnType
109
+ >[] =
110
+ // @ts-ignore
111
+ queryFilter[prop];
112
+
113
+ const compoundApiFilters = compoundFilters.map(
114
+ (i: QueryFilter<DatabaseSchemaType, ColumnNameToColumnType>) => {
115
+ return this.recursivelyBuildFilter(i);
116
+ }
117
+ );
118
+
119
+ // Either have an `and` or an `or` compound filter
120
+ let temp: apiFilterType = {
121
+ ...(prop === "and"
122
+ ? { and: compoundApiFilters }
123
+ : { or: compoundApiFilters }),
124
+ };
125
+ return temp;
126
+ } else {
127
+ const propType = this.propNameToColumnName[prop].type;
128
+ const temp: apiSingleFilter = {
129
+ property: this.propNameToColumnName[prop].columnName,
130
+ };
131
+
132
+ //@ts-ignore
133
+ temp[propType] = (queryFilter as SingleFilter<ColumnNameToColumnType>)[
134
+ prop
135
+ ];
136
+ return temp;
137
+ }
138
+ }
139
+ }
140
+ }
@@ -0,0 +1,421 @@
1
+ import {
2
+ DatabaseObjectResponse,
3
+ GetDatabaseResponse,
4
+ } from "@notionhq/client/build/src/api-endpoints";
5
+ import * as ts from "typescript";
6
+ import fs from "fs";
7
+ import path from "path";
8
+ import { DATABASES_DIR } from "./index";
9
+ import { NotionColumnTypes } from "queryTypes";
10
+
11
+ type propNameToColumnNameType = Record<
12
+ string,
13
+ { columnName: string; type: NotionColumnTypes }
14
+ >;
15
+
16
+ /*
17
+ Responsible for generating `.ts` files
18
+ */
19
+ export async function createTypescriptFileForDatabase(
20
+ dbResponse: GetDatabaseResponse
21
+ ) {
22
+ const {
23
+ id: databaseId,
24
+ properties,
25
+ title,
26
+ } = dbResponse as DatabaseObjectResponse;
27
+ const propNameToColumnName: propNameToColumnNameType = {};
28
+ const databaseName = title[0].plain_text;
29
+ const databaseClassName = camelize(databaseName).replace(/[^a-zA-Z0-9]/g, "");
30
+
31
+ const databaseColumnTypeProps: ts.TypeElement[] = [];
32
+
33
+ // Looping through each column of database
34
+ Object.values(properties).forEach((value) => {
35
+ const { type: columnType, name: columnName } = value;
36
+
37
+ // Taking the column name and camelizing it for typescript use
38
+ const camelizedColumnName = camelize(columnName);
39
+
40
+ // Creating map of column name to the column's name in the database's typescript type
41
+ propNameToColumnName[camelizedColumnName] = {
42
+ columnName,
43
+ type: columnType,
44
+ };
45
+
46
+ if (
47
+ columnType === "title" ||
48
+ columnType === "rich_text" ||
49
+ columnType === "email" ||
50
+ columnType === "phone_number"
51
+ ) {
52
+ // add text column to collection type
53
+ databaseColumnTypeProps.push(
54
+ createTextProperty({
55
+ name: camelizedColumnName,
56
+ isTitle: columnType === "title",
57
+ })
58
+ );
59
+ } else if (columnType === "number") {
60
+ // add number column to collection type
61
+ databaseColumnTypeProps.push(createNumberProperty(camelizedColumnName));
62
+ } else if (columnType === "url") {
63
+ // add url column to collection type
64
+ databaseColumnTypeProps.push(
65
+ createTextProperty({ name: camelizedColumnName, isTitle: false })
66
+ );
67
+ } else if (columnType === "date") {
68
+ // add Date column to collection type
69
+ databaseColumnTypeProps.push(createDateProperty(camelizedColumnName));
70
+ } else if (
71
+ columnType === "select" ||
72
+ columnType === "status" ||
73
+ columnType === "multi_select"
74
+ ) {
75
+ // @ts-ignore
76
+ const options = value[columnType].options.map((x) => x.name);
77
+ databaseColumnTypeProps.push(
78
+ createMultiOptionProp({
79
+ name: camelizedColumnName,
80
+ options,
81
+ isArray: columnType === "multi_select", // Union or Union Array
82
+ })
83
+ );
84
+ }
85
+ });
86
+
87
+ // Object type that represents the database schema
88
+ const DatabaseSchemaType = ts.factory.createTypeAliasDeclaration(
89
+ undefined,
90
+ ts.factory.createIdentifier("DatabaseSchemaType"),
91
+ undefined,
92
+ ts.factory.createTypeLiteralNode(databaseColumnTypeProps)
93
+ );
94
+
95
+ // Top level non-nested variable, functions, types for database files
96
+ const TsNodesForDatabaseFile = ts.factory.createNodeArray([
97
+ createDatabaseActionsClassImport(),
98
+ createDatabaseIdVariable(databaseId),
99
+ DatabaseSchemaType,
100
+ createColumnNameToColumnProperties(propNameToColumnName),
101
+ createColumnNameToColumnType(),
102
+ createDatabaseClassExport({ databaseName: databaseClassName }),
103
+ ]);
104
+
105
+ const sourceFile = ts.createSourceFile(
106
+ "",
107
+ "",
108
+ ts.ScriptTarget.ESNext,
109
+ true,
110
+ ts.ScriptKind.TS
111
+ );
112
+ const printer = ts.createPrinter();
113
+
114
+ const typescriptCodeToString = printer.printList(
115
+ ts.ListFormat.MultiLine,
116
+ TsNodesForDatabaseFile,
117
+ sourceFile
118
+ );
119
+ const transpileToJavaScript = ts.transpile(typescriptCodeToString, {
120
+ module: ts.ModuleKind.None,
121
+ target: ts.ScriptTarget.ESNext,
122
+ });
123
+
124
+ // Create databases output folder
125
+ if (!fs.existsSync(DATABASES_DIR)) {
126
+ fs.mkdirSync(DATABASES_DIR);
127
+ }
128
+
129
+ // Create TypeScript and JavaScript files
130
+ fs.writeFileSync(
131
+ path.resolve(DATABASES_DIR, `${databaseClassName}.ts`),
132
+ typescriptCodeToString
133
+ );
134
+ fs.writeFileSync(
135
+ path.resolve(DATABASES_DIR, `${databaseClassName}.js`),
136
+ transpileToJavaScript
137
+ );
138
+
139
+ return { databaseName, databaseClassName, databaseId };
140
+ }
141
+
142
+ // generate text property
143
+ function createTextProperty(args: { name: string; isTitle: boolean }) {
144
+ const { name, isTitle } = args;
145
+ const text = ts.factory.createPropertySignature(
146
+ undefined,
147
+ ts.factory.createIdentifier(name),
148
+ !isTitle ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined,
149
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)
150
+ );
151
+ return text;
152
+ }
153
+
154
+ /**
155
+ * Generate number property to go inside a type
156
+ * name: number
157
+ */
158
+ function createNumberProperty(name: string) {
159
+ const number = ts.factory.createPropertySignature(
160
+ undefined,
161
+ ts.factory.createIdentifier(name),
162
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken),
163
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword)
164
+ );
165
+ return number;
166
+ }
167
+
168
+ /**
169
+ * For selects and multi-select collection properties
170
+ * array = true for multi-select
171
+ */
172
+ function createMultiOptionProp(args: {
173
+ name: string;
174
+ options: string[];
175
+ isArray: boolean;
176
+ }) {
177
+ const { isArray, name, options } = args;
178
+ return ts.factory.createPropertySignature(
179
+ undefined,
180
+ ts.factory.createIdentifier(name),
181
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken),
182
+ isArray
183
+ ? ts.factory.createArrayTypeNode(
184
+ ts.factory.createParenthesizedType(
185
+ ts.factory.createUnionTypeNode([
186
+ ...options.map((option) =>
187
+ ts.factory.createLiteralTypeNode(
188
+ ts.factory.createStringLiteral(option)
189
+ )
190
+ ),
191
+ createOtherStringProp(),
192
+ ])
193
+ )
194
+ )
195
+ : ts.factory.createUnionTypeNode([
196
+ ...options.map((option) =>
197
+ ts.factory.createLiteralTypeNode(
198
+ ts.factory.createStringLiteral(option)
199
+ )
200
+ ),
201
+ createOtherStringProp(),
202
+ ])
203
+ );
204
+ }
205
+
206
+ // string & {}. Allows users to pass in values
207
+ function createOtherStringProp() {
208
+ return ts.factory.createIntersectionTypeNode([
209
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
210
+ ts.factory.createTypeLiteralNode([]),
211
+ ]);
212
+ }
213
+
214
+ function createDateProperty(name: string) {
215
+ return ts.factory.createPropertySignature(
216
+ undefined,
217
+ ts.factory.createIdentifier(name),
218
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken),
219
+ ts.factory.createTypeLiteralNode([
220
+ ts.factory.createPropertySignature(
221
+ undefined,
222
+ ts.factory.createIdentifier("start"),
223
+ undefined,
224
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)
225
+ ),
226
+ ts.factory.createPropertySignature(
227
+ undefined,
228
+ ts.factory.createIdentifier("end"),
229
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken),
230
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)
231
+ ),
232
+ ])
233
+ );
234
+ }
235
+
236
+ // Generate database Id variable
237
+ // const databaseId = <database-id>
238
+ function createDatabaseIdVariable(databaseId: string) {
239
+ return ts.factory.createVariableStatement(
240
+ undefined,
241
+ ts.factory.createVariableDeclarationList(
242
+ [
243
+ ts.factory.createVariableDeclaration(
244
+ ts.factory.createIdentifier("databaseId"),
245
+ undefined,
246
+ undefined,
247
+ ts.factory.createStringLiteral(databaseId)
248
+ ),
249
+ ],
250
+ ts.NodeFlags.Const
251
+ )
252
+ );
253
+ }
254
+
255
+ /**
256
+ * Instead of refering to the column names 1:1 such as "Book Rating", we transform them to
257
+ * camelcase (eg. bookRating). So we need to keep track of the original name and the type
258
+ * for when we construct request for API
259
+ *
260
+ * Example
261
+ *
262
+ * const columnNameToColumnProperties = {
263
+ *
264
+ * "bookRating": {
265
+ * columnName: "Book Rating",
266
+ * type: "select"
267
+ * },
268
+ * "genre": {
269
+ * columnName: "Genre",
270
+ * type: "multi_select"
271
+ * }
272
+ *
273
+ * }
274
+ */
275
+ function createColumnNameToColumnProperties(colMap: propNameToColumnNameType) {
276
+ return ts.factory.createVariableDeclarationList(
277
+ [
278
+ ts.factory.createVariableDeclaration(
279
+ ts.factory.createIdentifier("columnNameToColumnProperties"),
280
+ undefined,
281
+ undefined,
282
+ ts.factory.createAsExpression(
283
+ ts.factory.createObjectLiteralExpression(
284
+ [
285
+ ...Object.entries(colMap).map(([propName, value]) =>
286
+ ts.factory.createPropertyAssignment(
287
+ ts.factory.createStringLiteral(propName),
288
+ ts.factory.createObjectLiteralExpression(
289
+ [
290
+ ts.factory.createPropertyAssignment(
291
+ ts.factory.createIdentifier("columnName"),
292
+ ts.factory.createStringLiteral(value.columnName)
293
+ ),
294
+ ts.factory.createPropertyAssignment(
295
+ ts.factory.createIdentifier("type"),
296
+ ts.factory.createStringLiteral(value.type)
297
+ ),
298
+ ],
299
+ true
300
+ )
301
+ )
302
+ ),
303
+ ],
304
+ true
305
+ ),
306
+ ts.factory.createTypeReferenceNode(
307
+ ts.factory.createIdentifier("const"),
308
+ undefined
309
+ )
310
+ )
311
+ ),
312
+ ],
313
+ ts.NodeFlags.Const
314
+ );
315
+ }
316
+
317
+ function createColumnNameToColumnType() {
318
+ return ts.factory.createTypeAliasDeclaration(
319
+ undefined,
320
+ ts.factory.createIdentifier("ColumnNameToColumnType"),
321
+ undefined,
322
+ ts.factory.createMappedTypeNode(
323
+ undefined,
324
+ ts.factory.createTypeParameterDeclaration(
325
+ undefined,
326
+ ts.factory.createIdentifier("Property"),
327
+ ts.factory.createTypeOperatorNode(
328
+ ts.SyntaxKind.KeyOfKeyword,
329
+ ts.factory.createTypeQueryNode(
330
+ ts.factory.createIdentifier("columnNameToColumnProperties"),
331
+ undefined
332
+ )
333
+ ),
334
+ undefined
335
+ ),
336
+ undefined,
337
+ undefined,
338
+ ts.factory.createIndexedAccessTypeNode(
339
+ ts.factory.createIndexedAccessTypeNode(
340
+ ts.factory.createTypeQueryNode(
341
+ ts.factory.createIdentifier("columnNameToColumnProperties"),
342
+ undefined
343
+ ),
344
+ ts.factory.createTypeReferenceNode(
345
+ ts.factory.createIdentifier("Property"),
346
+ undefined
347
+ )
348
+ ),
349
+ ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral("type"))
350
+ ),
351
+ undefined
352
+ /* unknown */
353
+ )
354
+ );
355
+ }
356
+
357
+ // Need to import the database class used to execute database actions (adding + querying)
358
+ function createDatabaseActionsClassImport() {
359
+ return ts.factory.createImportDeclaration(
360
+ undefined,
361
+ ts.factory.createImportClause(
362
+ false,
363
+ undefined,
364
+ ts.factory.createNamedImports([
365
+ ts.factory.createImportSpecifier(
366
+ false,
367
+ undefined,
368
+ ts.factory.createIdentifier("DatabaseActions")
369
+ ),
370
+ ])
371
+ ),
372
+ ts.factory.createStringLiteral("../src/DatabaseActions"),
373
+ undefined
374
+ );
375
+ }
376
+
377
+ /**
378
+ * Create export statement for the database class
379
+ * export const <databaseName> = new DatabaseActions<DatabaseSchemaType>(datbaseId, columnNameToColumnProperties)
380
+ */
381
+ function createDatabaseClassExport(args: { databaseName: string }) {
382
+ const { databaseName } = args;
383
+ return ts.factory.createVariableStatement(
384
+ [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
385
+ ts.factory.createVariableDeclarationList(
386
+ [
387
+ ts.factory.createVariableDeclaration(
388
+ ts.factory.createIdentifier(databaseName),
389
+ undefined,
390
+ undefined,
391
+ ts.factory.createNewExpression(
392
+ ts.factory.createIdentifier("DatabaseActions"),
393
+ [
394
+ ts.factory.createTypeReferenceNode(
395
+ ts.factory.createIdentifier("DatabaseSchemaType"),
396
+ undefined
397
+ ),
398
+ ts.factory.createTypeReferenceNode(
399
+ ts.factory.createIdentifier("ColumnNameToColumnType"),
400
+ undefined
401
+ ),
402
+ ],
403
+ [
404
+ ts.factory.createIdentifier("databaseId"),
405
+ ts.factory.createIdentifier("columnNameToColumnProperties"),
406
+ ]
407
+ )
408
+ ),
409
+ ],
410
+ ts.NodeFlags.Const
411
+ )
412
+ );
413
+ }
414
+
415
+ // for a type's property name
416
+ function camelize(str: string) {
417
+ return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {
418
+ if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
419
+ return index === 0 ? match.toLowerCase() : match.toUpperCase();
420
+ });
421
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,40 @@
1
+ #! /usr/bin/env node
2
+
3
+ import fs from "fs";
4
+ import { createDatabaseTypes } from "./index";
5
+ import path from "path";
6
+
7
+ async function main() {
8
+ const args = process.argv.slice(2);
9
+
10
+ if (args.length === 1 && args[0] === "generate") {
11
+ const projDir = process.cwd();
12
+
13
+ const notionConfigDirJS = fs.existsSync(
14
+ path.join(projDir, "notion.config.js")
15
+ );
16
+ const notionConfigDirTS = fs.existsSync(
17
+ path.join(projDir, "notion.config.ts")
18
+ );
19
+
20
+ console.log(path.join(projDir, "notion.config"));
21
+ if (notionConfigDirJS || notionConfigDirTS) {
22
+ const config = require(path.join(projDir, "notion.config"));
23
+
24
+ const { databaseNames } = await createDatabaseTypes(config);
25
+ if (databaseNames.length < 0) {
26
+ console.log("generated no types");
27
+ } else {
28
+ console.log("Generated types for the following Database's: ");
29
+ for (let x = 0; x < databaseNames.length; x++) {
30
+ console.log(`${x}. ${databaseNames[x]}`);
31
+ }
32
+ }
33
+ } else {
34
+ console.error("Could not find file `notion.config.ts` in root");
35
+ process.exit(1);
36
+ }
37
+ }
38
+ }
39
+
40
+ main();
package/src/index.ts ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Responsible for consuming notion.config.js
3
+ */
4
+
5
+ import { Client } from "@notionhq/client";
6
+ import { GetDatabaseResponse } from "@notionhq/client/build/src/api-endpoints";
7
+ import { createTypescriptFileForDatabase } from "./GenerateTypes";
8
+ import * as ts from "typescript";
9
+ import fs from "fs";
10
+ import path from "path";
11
+
12
+ export const DATABASES_DIR = path.join(__dirname, "../../build", "databases");
13
+
14
+ export type NotionConfigType = {
15
+ auth: string;
16
+ databaseIds: string[];
17
+ };
18
+
19
+ export const createDatabaseTypes = async (args: NotionConfigType) => {
20
+ const { auth, databaseIds } = args;
21
+
22
+ // Making sure the user is passing valid arguments
23
+ if (!auth) {
24
+ console.error("Please pass a valid Notion Integration Key");
25
+ process.exit(1);
26
+ }
27
+
28
+ if (databaseIds.length < 0) {
29
+ console.error("Please pass some database Ids");
30
+ process.exit(1);
31
+ }
32
+
33
+ // Initialize client
34
+ const NotionClient = new Client({
35
+ auth: auth,
36
+ });
37
+
38
+ const databaseNames: string[] = [];
39
+ const databaseClassExportStatements: ts.ExportDeclaration[] = [];
40
+
41
+ // Remove the previous databases, so they can call get updated
42
+ fs.rmdir(DATABASES_DIR, () =>
43
+ console.log("Deleting current database types...")
44
+ );
45
+
46
+ for (const database_id of databaseIds) {
47
+ let dbOjbect: GetDatabaseResponse;
48
+
49
+ try {
50
+ // Get the database schema
51
+ dbOjbect = await NotionClient.databases.retrieve({
52
+ database_id,
53
+ });
54
+
55
+ // Create typescript file based on schema
56
+ const { databaseClassName, databaseId, databaseName } =
57
+ await createTypescriptFileForDatabase(dbOjbect);
58
+
59
+ databaseNames.push(databaseName);
60
+ databaseClassExportStatements.push(
61
+ databaseExportStatement({
62
+ databaseClassName,
63
+ })
64
+ );
65
+ } catch (e) {
66
+ console.error(e);
67
+ return { databaseNames: [] };
68
+ }
69
+ }
70
+
71
+ // Create a file that exports all databases
72
+ createDatabaseBarrelFile({
73
+ databaseClassExportStatements,
74
+ });
75
+ return { databaseNames };
76
+ };
77
+
78
+ // Create the export statement for database file file
79
+ // export { databaseName } from "./databaseName"
80
+ function databaseExportStatement(args: { databaseClassName: string }) {
81
+ const { databaseClassName } = args;
82
+ return ts.factory.createExportDeclaration(
83
+ undefined,
84
+ false,
85
+ ts.factory.createNamedExports([
86
+ ts.factory.createExportSpecifier(
87
+ false,
88
+ undefined,
89
+ ts.factory.createIdentifier(databaseClassName)
90
+ ),
91
+ ]),
92
+ ts.factory.createStringLiteral(`./${databaseClassName}`),
93
+ undefined
94
+ );
95
+ }
96
+
97
+ // Creates file that import all generated notion database Ids
98
+ function createDatabaseBarrelFile(args: {
99
+ databaseClassExportStatements: ts.Node[];
100
+ }) {
101
+ const { databaseClassExportStatements } = args;
102
+ const nodes = ts.factory.createNodeArray(databaseClassExportStatements);
103
+ const sourceFile = ts.createSourceFile(
104
+ "placeholder.ts",
105
+ "",
106
+ ts.ScriptTarget.ESNext,
107
+ true,
108
+ ts.ScriptKind.TS
109
+ );
110
+ const printer = ts.createPrinter();
111
+
112
+ const typescriptCodeToString = printer.printList(
113
+ ts.ListFormat.MultiLine,
114
+ nodes,
115
+ sourceFile
116
+ );
117
+
118
+ const transpileToJavaScript = ts.transpile(typescriptCodeToString, {
119
+ module: ts.ModuleKind.None,
120
+ target: ts.ScriptTarget.ES2015,
121
+ });
122
+
123
+ if (!fs.existsSync(DATABASES_DIR)) {
124
+ fs.mkdirSync(DATABASES_DIR);
125
+ }
126
+
127
+ // Create TypeScript and JavaScript file
128
+ fs.writeFileSync(
129
+ path.resolve(DATABASES_DIR, "index.ts"),
130
+ typescriptCodeToString
131
+ );
132
+ fs.writeFileSync(
133
+ path.resolve(DATABASES_DIR, "index.js"),
134
+ transpileToJavaScript
135
+ );
136
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Column types' for all query options
3
+ */
4
+ // import { PageObjectResponse }
5
+
6
+ import { PageObjectResponse } from "@notionhq/client/build/src/api-endpoints";
7
+
8
+ type columnDiscriminatedUnionTypes = PageObjectResponse["properties"];
9
+ export type NotionColumnTypes =
10
+ columnDiscriminatedUnionTypes[keyof columnDiscriminatedUnionTypes]["type"];
11
+ // type SupportedQueryableNotionColumnTypes = Exclude<NotionColumnTypes, "created_by" | >
12
+
13
+ export type SupportedNotionColumnTypes = Exclude<
14
+ NotionColumnTypes,
15
+ | "formula"
16
+ | "files"
17
+ | "people"
18
+ | "relation"
19
+ | "rollup"
20
+ | "created_by"
21
+ | "last_edited_by"
22
+ | "created_time"
23
+ | "last_edited_time"
24
+ >;
25
+
26
+ type TextPropertyFilters = {
27
+ equals: string;
28
+ does_not_equal: string;
29
+ contains: string;
30
+ does_not_contain: string;
31
+ starts_with: string;
32
+ ends_with: string;
33
+ is_empty: true;
34
+ is_not_empty: true;
35
+ };
36
+
37
+ type NumberPropertyFilters = {
38
+ equals: number;
39
+ does_not_equals: number;
40
+ greater_than: number;
41
+ less_than: number;
42
+ greater_than_or_equal_to: number;
43
+ less_than_or_equal_to: number;
44
+ is_empty: true;
45
+ is_not_empty: true;
46
+ };
47
+
48
+ type CheckBoxPropertyFilters = {
49
+ equals: boolean;
50
+ does_not_equal: boolean;
51
+ };
52
+
53
+ //
54
+ type SelectPropertyFilters<T> = {
55
+ equals: (T extends Array<any> ? T[number] : T) | (string & {});
56
+ does_not_equal: (T extends Array<any> ? T[number] : T) | (string & {});
57
+ is_empty: true;
58
+ is_not_empty: true;
59
+ };
60
+
61
+ // pay in array --> need to turn into union
62
+ type MultiSelectPropertyFilters<T> = {
63
+ contains: (T extends Array<any> ? T[number] : T) | (string & {});
64
+ does_not_contain: (T extends Array<any> ? T[number] : T) | (string & {});
65
+ is_empty: true;
66
+ is_not_empty: true;
67
+ };
68
+
69
+ type StatusPropertyFilters<T> = SelectPropertyFilters<T>;
70
+
71
+ type ISO8601Date = string;
72
+ type DatePropertyFilters = {
73
+ equals: ISO8601Date;
74
+ before: ISO8601Date;
75
+ after: ISO8601Date;
76
+ on_or_before: ISO8601Date;
77
+ is_empty: true;
78
+ is_not_empty: true;
79
+ on_or_after: string;
80
+ past_week: {};
81
+ past_month: {};
82
+ past_year: {};
83
+ this_week: {};
84
+ next_week: {};
85
+ next_month: {};
86
+ next_year: {};
87
+ };
88
+
89
+ export type FilterOptions<T = []> = {
90
+ rich_text: TextPropertyFilters;
91
+ title: TextPropertyFilters;
92
+ number: NumberPropertyFilters;
93
+ checkbox: CheckBoxPropertyFilters;
94
+ select: SelectPropertyFilters<T>;
95
+ multi_select: MultiSelectPropertyFilters<T>;
96
+ url: TextPropertyFilters;
97
+ date: DatePropertyFilters;
98
+ status: StatusPropertyFilters<T>;
99
+ email: TextPropertyFilters;
100
+ phone_number: TextPropertyFilters;
101
+ };
102
+
103
+ /**
104
+ * Types to build query object user types out
105
+ */
106
+
107
+ type ColumnNameToNotionColumnType<T> = Record<
108
+ keyof T,
109
+ SupportedNotionColumnTypes
110
+ >;
111
+ type ColumnNameToPossibleValues = Record<string, any>;
112
+ // T is a column name to column type
113
+ // Y is the collection type
114
+ export type SingleFilter<
115
+ Y extends Record<string, any>,
116
+ T extends ColumnNameToNotionColumnType<Y>
117
+ > = {
118
+ // Passing the type from collection
119
+ [Property in keyof Y]?: Partial<FilterOptions<Y[Property]>[T[Property]]>;
120
+ };
121
+
122
+ export type CompoundFilters<
123
+ Y extends Record<string, any>,
124
+ T extends Record<keyof Y, SupportedNotionColumnTypes>
125
+ > =
126
+ | { and: Array<SingleFilter<Y, T> | CompoundFilters<Y, T>> }
127
+ | { or: Array<SingleFilter<Y, T> | CompoundFilters<Y, T>> };
128
+
129
+ export type QueryFilter<
130
+ Y extends Record<string, any>,
131
+ T extends Record<keyof Y, SupportedNotionColumnTypes>
132
+ > = SingleFilter<Y, T> | CompoundFilters<Y, T>;
133
+
134
+ export type Query<
135
+ Y extends Record<string, any>,
136
+ T extends Record<keyof Y, SupportedNotionColumnTypes>
137
+ > = {
138
+ filter?: QueryFilter<Y, T>;
139
+ sort?: [];
140
+ };
141
+
142
+ export type apiFilterQuery = {
143
+ filter?: apiSingleFilter | apiAndFilter | apiOrFilter;
144
+ };
145
+
146
+ /**
147
+ * Transform the types above to build types to
148
+ * actually build schema for query request
149
+ */
150
+
151
+ type apiColumnTypeToOptions = {
152
+ [prop in keyof FilterOptions]?: Partial<FilterOptions[prop]>;
153
+ };
154
+ export interface apiSingleFilter extends apiColumnTypeToOptions {
155
+ property: string;
156
+ }
157
+
158
+ export type apiFilterType =
159
+ | apiSingleFilter
160
+ | apiAndFilter
161
+ | apiOrFilter
162
+ | undefined;
163
+ type apiAndFilter = {
164
+ and: Array<apiFilterType>;
165
+ };
166
+
167
+ type apiOrFilter = {
168
+ or: Array<apiFilterType>;
169
+ };