@haustle/notion-orm 0.0.37 → 0.0.41

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.
Files changed (39) hide show
  1. package/README.md +126 -0
  2. package/build/src/BuildCall.d.ts +15 -2
  3. package/build/src/BuildCall.d.ts.map +1 -1
  4. package/build/src/BuildCall.js +35 -2
  5. package/build/src/BuildCall.js.map +1 -1
  6. package/build/src/DatabaseActions.d.ts +3 -4
  7. package/build/src/DatabaseActions.d.ts.map +1 -1
  8. package/build/src/DatabaseActions.js +7 -2
  9. package/build/src/DatabaseActions.js.map +1 -1
  10. package/build/src/GenerateTypes.d.ts +0 -3
  11. package/build/src/GenerateTypes.d.ts.map +1 -1
  12. package/build/src/GenerateTypes.js +49 -58
  13. package/build/src/GenerateTypes.js.map +1 -1
  14. package/build/src/cli.js +2 -4
  15. package/build/src/cli.js.map +1 -1
  16. package/build/src/index.d.ts +12 -0
  17. package/build/src/index.d.ts.map +1 -0
  18. package/build/src/{NotionConfig.js → index.js} +21 -15
  19. package/build/src/index.js.map +1 -0
  20. package/build/src/queryTypes.d.ts +22 -11
  21. package/build/src/queryTypes.d.ts.map +1 -1
  22. package/build/src/queryTypes.js +0 -6
  23. package/build/src/queryTypes.js.map +1 -1
  24. package/package.json +3 -5
  25. package/build/databases/5f4bf76a-1e3f-48d6-84d2-506ea2690d64.js +0 -28
  26. package/build/databases/5f4bf76a-1e3f-48d6-84d2-506ea2690d64.ts +0 -34
  27. package/build/databases/a52239e4-839d-4a3a-8f48-75376cfbfb02.js +0 -24
  28. package/build/databases/a52239e4-839d-4a3a-8f48-75376cfbfb02.ts +0 -30
  29. package/build/databases/notion.js +0 -2
  30. package/build/databases/notion.ts +0 -2
  31. package/build/src/NotionConfig.d.ts +0 -9
  32. package/build/src/NotionConfig.d.ts.map +0 -1
  33. package/build/src/NotionConfig.js.map +0 -1
  34. package/src/BuildCall.ts +0 -85
  35. package/src/DatabaseActions.ts +0 -134
  36. package/src/GenerateTypes.ts +0 -424
  37. package/src/NotionConfig.ts +0 -132
  38. package/src/cli.ts +0 -43
  39. package/src/queryTypes.ts +0 -160
@@ -1,424 +0,0 @@
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 "./NotionConfig";
9
-
10
- // This can be grabbed from // api-endpoints.d.ts with some work
11
- const propertyArr = [
12
- "text",
13
- "select",
14
- "title",
15
- "number",
16
- "multi_select",
17
- "checkbox",
18
- "url",
19
- ];
20
- export type PropertyType = typeof propertyArr[number];
21
-
22
- type propNameToColumnNameType = Record<
23
- string,
24
- { columnName: string; type: PropertyType }
25
- >;
26
-
27
- /*
28
- Responsible for generating `.ts` files
29
- */
30
- export async function createTypescriptFileForDatabase(
31
- dbResponse: GetDatabaseResponse
32
- ) {
33
- const {
34
- id: databaseId,
35
- properties,
36
- title,
37
- } = dbResponse as DatabaseObjectResponse;
38
- const propNameToColumnName: propNameToColumnNameType = {};
39
- const databaseName = title[0].plain_text;
40
- const databaseClassName = camelize(databaseName).replace(/[^a-zA-Z0-9]/g, "");
41
-
42
- const databaseColumnTypeProps: ts.TypeElement[] = [];
43
-
44
- // Looping through each column of database
45
- Object.values(properties).forEach((value) => {
46
- const { type: columnType, name: columnName } = value;
47
-
48
- // Taking the column name and camelizing it for typescript use
49
- const camelizedColumnName = camelize(columnName);
50
-
51
- // Creating map of column name to the column's name in the database's typescript type
52
- propNameToColumnName[camelizedColumnName] = {
53
- columnName,
54
- type: columnType,
55
- };
56
-
57
- if (columnType === "title" || columnType === "rich_text") {
58
- // add text column to collection type
59
- databaseColumnTypeProps.push(
60
- createTextProperty(camelizedColumnName, columnType === "title")
61
- );
62
- } else if (columnType === "number") {
63
- // add number column to collection type
64
- databaseColumnTypeProps.push(createNumberProperty(camelizedColumnName));
65
- } else if (columnType === "url") {
66
- // add url column to collection type
67
- databaseColumnTypeProps.push(
68
- createTextProperty(camelizedColumnName, false)
69
- );
70
- } else if (columnType === "date") {
71
- // add Date column to collection type
72
- databaseColumnTypeProps.push(createDateProperty(camelizedColumnName));
73
- } else if (columnType == "select" || columnType == "multi_select") {
74
- // @ts-ignore
75
- const options = value[columnType].options.map((x) => x.name);
76
- databaseColumnTypeProps.push(
77
- createMultiOptionProp(
78
- camelizedColumnName,
79
- options,
80
- // This determines whether the property needs to be a union or a union array
81
- columnType === "multi_select"
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
- importCollectionClass(),
98
- createDatabaseIdVariable(databaseId),
99
- DatabaseSchemaType,
100
- mapPropNameToColumnDetails(propNameToColumnName),
101
- ColumnNameToColumnType(),
102
- exportDatabaseActions(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
-
120
- const transpileToJavaScript = ts.transpile(typescriptCodeToString, {
121
- module: ts.ModuleKind.None,
122
- target: ts.ScriptTarget.ES2015,
123
- });
124
-
125
- // Create our output folder
126
- if (!fs.existsSync(DATABASES_DIR)) {
127
- fs.mkdirSync(DATABASES_DIR);
128
- }
129
-
130
- // Create TypeScript and JavaScript files
131
- fs.writeFileSync(
132
- path.resolve(DATABASES_DIR, `${databaseId}.ts`),
133
- typescriptCodeToString
134
- );
135
- fs.writeFileSync(
136
- path.resolve(DATABASES_DIR, `${databaseId}.js`),
137
- transpileToJavaScript
138
- );
139
-
140
- return { databaseName, databaseClassName, databaseId };
141
- }
142
-
143
- // generate text property
144
- function createTextProperty(name: string, isTitle: boolean) {
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
- *
170
- * @param name name of property
171
- * @param options
172
- * @param array
173
- * @returns
174
- *
175
- * For selects and multi-select collection properties
176
- *
177
- * array = true for multi-select
178
- *
179
- * name = ("x" | "y" | "z")[]
180
- */
181
- function createMultiOptionProp(
182
- name: string,
183
- options: string[],
184
- array: boolean
185
- ) {
186
- return ts.factory.createPropertySignature(
187
- undefined,
188
- ts.factory.createIdentifier(name),
189
- ts.factory.createToken(ts.SyntaxKind.QuestionToken),
190
- array
191
- ? ts.factory.createArrayTypeNode(
192
- ts.factory.createParenthesizedType(
193
- ts.factory.createUnionTypeNode([
194
- ...options.map((option) =>
195
- ts.factory.createLiteralTypeNode(
196
- ts.factory.createStringLiteral(option)
197
- )
198
- ),
199
- createOtherStringProp(),
200
- ])
201
- )
202
- )
203
- : ts.factory.createUnionTypeNode([
204
- ...options.map((option) =>
205
- ts.factory.createLiteralTypeNode(
206
- ts.factory.createStringLiteral(option)
207
- )
208
- ),
209
- createOtherStringProp(),
210
- ])
211
- );
212
- }
213
-
214
- // string & {}. Allows users to pass in values
215
- function createOtherStringProp() {
216
- return ts.factory.createIntersectionTypeNode([
217
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
218
- ts.factory.createTypeLiteralNode([]),
219
- ]);
220
- }
221
- function createDateProperty(name: string) {
222
- return ts.factory.createPropertySignature(
223
- undefined,
224
- ts.factory.createIdentifier(name),
225
- ts.factory.createToken(ts.SyntaxKind.QuestionToken),
226
- ts.factory.createTypeReferenceNode(
227
- ts.factory.createIdentifier("Date"),
228
- undefined
229
- )
230
- );
231
- }
232
-
233
- // Generate database Id variable
234
- // const databaseId = <database-id>
235
- function createDatabaseIdVariable(databaseId: string) {
236
- return ts.factory.createVariableStatement(
237
- undefined,
238
- ts.factory.createVariableDeclarationList(
239
- [
240
- ts.factory.createVariableDeclaration(
241
- ts.factory.createIdentifier("databaseId"),
242
- undefined,
243
- undefined,
244
- ts.factory.createStringLiteral(databaseId)
245
- ),
246
- ],
247
- ts.NodeFlags.Const
248
- )
249
- );
250
- }
251
-
252
- /**
253
- * Instead of refering to the column names 1:1 such as "Book Rating", we transform them to
254
- * camelcase (eg. bookRating). So we need to keep track of the original name and the type
255
- * for when we construct request for API
256
- *
257
- * Example
258
- *
259
- * const propMap = {
260
- *
261
- * "bookRating": {
262
- * columnName: "Book Rating",
263
- * type: "select"
264
- * },
265
- * "genre": {
266
- * columnName: "Genre",
267
- * type: "multi_select"
268
- * }
269
- *
270
- * }
271
- * @param colMap
272
- * @returns
273
- */
274
- function mapPropNameToColumnDetails(colMap: propNameToColumnNameType) {
275
- return ts.factory.createVariableDeclarationList(
276
- [
277
- ts.factory.createVariableDeclaration(
278
- ts.factory.createIdentifier("propMap"),
279
- undefined,
280
- undefined,
281
- ts.factory.createAsExpression(
282
- ts.factory.createObjectLiteralExpression(
283
- [
284
- ...Object.entries(colMap).map(([propName, value]) =>
285
- ts.factory.createPropertyAssignment(
286
- ts.factory.createStringLiteral(propName),
287
- ts.factory.createObjectLiteralExpression(
288
- [
289
- ts.factory.createPropertyAssignment(
290
- ts.factory.createIdentifier("columnName"),
291
- ts.factory.createStringLiteral(value.columnName)
292
- ),
293
- ts.factory.createPropertyAssignment(
294
- ts.factory.createIdentifier("type"),
295
- ts.factory.createStringLiteral(value.type)
296
- ),
297
- ],
298
- true
299
- )
300
- )
301
- ),
302
- ],
303
- true
304
- ),
305
- ts.factory.createTypeReferenceNode(
306
- ts.factory.createIdentifier("const"),
307
- undefined
308
- )
309
- )
310
- ),
311
- ],
312
- ts.NodeFlags.Const
313
- );
314
- }
315
-
316
- function ColumnNameToColumnType() {
317
- return ts.factory.createTypeAliasDeclaration(
318
- undefined,
319
- ts.factory.createIdentifier("ColumnNameToColumnType"),
320
- undefined,
321
- ts.factory.createMappedTypeNode(
322
- undefined,
323
- ts.factory.createTypeParameterDeclaration(
324
- undefined,
325
- ts.factory.createIdentifier("Property"),
326
- ts.factory.createTypeOperatorNode(
327
- ts.SyntaxKind.KeyOfKeyword,
328
- ts.factory.createTypeQueryNode(
329
- ts.factory.createIdentifier("propMap"),
330
- undefined
331
- )
332
- ),
333
- undefined
334
- ),
335
- undefined,
336
- undefined,
337
- ts.factory.createIndexedAccessTypeNode(
338
- ts.factory.createIndexedAccessTypeNode(
339
- ts.factory.createTypeQueryNode(
340
- ts.factory.createIdentifier("propMap"),
341
- undefined
342
- ),
343
- ts.factory.createTypeReferenceNode(
344
- ts.factory.createIdentifier("Property"),
345
- undefined
346
- )
347
- ),
348
- ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral("type"))
349
- ),
350
- undefined
351
- /* unknown */
352
- )
353
- );
354
- }
355
-
356
- // Need to import the class responsible for adding and querying the database
357
- function importCollectionClass() {
358
- return ts.factory.createImportDeclaration(
359
- undefined,
360
- ts.factory.createImportClause(
361
- false,
362
- undefined,
363
- ts.factory.createNamedImports([
364
- ts.factory.createImportSpecifier(
365
- false,
366
- undefined,
367
- ts.factory.createIdentifier("DatabaseActions")
368
- ),
369
- ])
370
- ),
371
- ts.factory.createStringLiteral("../src/DatabaseActions"),
372
- undefined
373
- );
374
- }
375
-
376
- // We export the database with the class above.
377
- // export
378
-
379
- /**
380
- * We export the database with
381
- * @param databaseName
382
- *
383
- * const <datbase-name> = new DatabaseActions<DatabaseSchemaType>(datbaseId, propMap)
384
- */
385
- function exportDatabaseActions(databaseName: string) {
386
- return ts.factory.createVariableStatement(
387
- [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
388
- ts.factory.createVariableDeclarationList(
389
- [
390
- ts.factory.createVariableDeclaration(
391
- ts.factory.createIdentifier(databaseName),
392
- undefined,
393
- undefined,
394
- ts.factory.createNewExpression(
395
- ts.factory.createIdentifier("DatabaseActions"),
396
- [
397
- ts.factory.createTypeReferenceNode(
398
- ts.factory.createIdentifier("DatabaseSchemaType"),
399
- undefined
400
- ),
401
- ts.factory.createTypeReferenceNode(
402
- ts.factory.createIdentifier("ColumnNameToColumnType"),
403
- undefined
404
- ),
405
- ],
406
- [
407
- ts.factory.createIdentifier("databaseId"),
408
- ts.factory.createIdentifier("propMap"),
409
- ]
410
- )
411
- ),
412
- ],
413
- ts.NodeFlags.Const
414
- )
415
- );
416
- }
417
-
418
- // for a type's property name
419
- function camelize(str: string) {
420
- return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {
421
- if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
422
- return index === 0 ? match.toLowerCase() : match.toUpperCase();
423
- });
424
- }
@@ -1,132 +0,0 @@
1
- import { Client } from "@notionhq/client";
2
- import { GetDatabaseResponse } from "@notionhq/client/build/src/api-endpoints";
3
- import { createTypescriptFileForDatabase } from "./GenerateTypes";
4
- import * as ts from "typescript";
5
- import fs from "fs";
6
- import path from "path";
7
- require("dotenv").config();
8
-
9
- export const DATABASES_DIR = path.join(__dirname, "../../build", "databases");
10
-
11
- export type NotionConfigType = {
12
- auth: string;
13
- databaseIds: string[];
14
- };
15
-
16
- type importClassType = {
17
- databaseId: string;
18
- databaseClassName: string;
19
- };
20
-
21
- export const createDatabaseTypes = async (notionInfo: NotionConfigType) => {
22
- const { auth, databaseIds } = notionInfo;
23
-
24
- // Making sure the user is passing valid arguments
25
- if (!auth) {
26
- console.error("Please pass a valid Notion Integration Key");
27
- process.exit(1);
28
- }
29
-
30
- if (databaseIds.length < 0) {
31
- console.error("Please pass some database Ids");
32
- process.exit(1);
33
- }
34
-
35
- // Initialize client
36
- const NotionClient = new Client({
37
- auth: auth,
38
- });
39
-
40
- const databaseNames: string[] = [];
41
- const databaseClassExportStatements: ts.ExportDeclaration[] = [];
42
-
43
- // Remove the previous databases, so they can call get updated
44
- fs.rmdir(DATABASES_DIR, () =>
45
- console.log("Deleting current database types...")
46
- );
47
-
48
- for (const database_id of databaseIds) {
49
- let dbOjbect: GetDatabaseResponse;
50
-
51
- try {
52
- // Get the database schema
53
- dbOjbect = await NotionClient.databases.retrieve({
54
- database_id,
55
- });
56
-
57
- // Create typescript file based on schema
58
- const { databaseClassName, databaseId, databaseName } =
59
- await createTypescriptFileForDatabase(dbOjbect);
60
-
61
- databaseNames.push(databaseName);
62
- databaseClassExportStatements.push(
63
- databaseExportStatement({
64
- databaseClassName,
65
- databaseId,
66
- })
67
- );
68
- } catch (e) {
69
- console.error(e);
70
- return { databaseNames: [] };
71
- }
72
- }
73
-
74
- // Create a file that exports all databases
75
- createNotionFile([...databaseClassExportStatements]);
76
- return { databaseNames };
77
- };
78
-
79
- // Create the import statement for notion.ts file
80
- function databaseExportStatement(dbClass: importClassType) {
81
- return ts.factory.createExportDeclaration(
82
- undefined,
83
- false,
84
- ts.factory.createNamedExports([
85
- ts.factory.createExportSpecifier(
86
- false,
87
- undefined,
88
- ts.factory.createIdentifier(dbClass.databaseClassName)
89
- ),
90
- ]),
91
- ts.factory.createStringLiteral(`./${dbClass.databaseId}`),
92
- undefined
93
- );
94
- }
95
-
96
- // Creates file that import all generated notion database Ids
97
- function createNotionFile(nodeArr: ts.Node[]) {
98
- const nodes = ts.factory.createNodeArray(nodeArr);
99
- const sourceFile = ts.createSourceFile(
100
- "placeholder.ts",
101
- "",
102
- ts.ScriptTarget.ESNext,
103
- true,
104
- ts.ScriptKind.TS
105
- );
106
- const printer = ts.createPrinter();
107
-
108
- const typescriptCodeToString = printer.printList(
109
- ts.ListFormat.MultiLine,
110
- nodes,
111
- sourceFile
112
- );
113
-
114
- const transpileToJavaScript = ts.transpile(typescriptCodeToString, {
115
- module: ts.ModuleKind.None,
116
- target: ts.ScriptTarget.ES2015,
117
- });
118
-
119
- if (!fs.existsSync(DATABASES_DIR)) {
120
- fs.mkdirSync(DATABASES_DIR);
121
- }
122
-
123
- // Create TypeScript and JavaScript file
124
- fs.writeFileSync(
125
- path.resolve(DATABASES_DIR, "notion.ts"),
126
- typescriptCodeToString
127
- );
128
- fs.writeFileSync(
129
- path.resolve(DATABASES_DIR, "notion.js"),
130
- typescriptCodeToString
131
- );
132
- }
package/src/cli.ts DELETED
@@ -1,43 +0,0 @@
1
- #! /usr/bin/env node
2
-
3
- import fs from "fs";
4
- import { createDatabaseTypes } from "./NotionConfig";
5
- import path from "path";
6
- require("dotenv").config();
7
-
8
- async function main() {
9
- const args = process.argv.slice(2);
10
-
11
- if (args.length === 1 && args[0] === "generate") {
12
- const projDir = process.cwd();
13
-
14
- const notionConfigDirJS = fs.existsSync(
15
- path.join(projDir, "notion.config.js")
16
- );
17
- const notionConfigDirTS = fs.existsSync(
18
- path.join(projDir, "notion.config.ts")
19
- );
20
-
21
- console.log(path.join(projDir, "notion.config"));
22
- if (notionConfigDirJS || notionConfigDirTS) {
23
- // this is a relative import, so we can escape out
24
-
25
- const config = require(path.join(projDir, "notion.config"));
26
-
27
- const { databaseNames } = await createDatabaseTypes(config);
28
- if (databaseNames.length < 0) {
29
- console.log("generated no types");
30
- } else {
31
- console.log("Generated types for the following Database's: ");
32
- for (let x = 0; x < databaseNames.length; x++) {
33
- console.log(`${x}. ${databaseNames[x]}`);
34
- }
35
- }
36
- } else {
37
- console.error("Could not find file `notion.config.ts` in root");
38
- process.exit(1);
39
- }
40
- }
41
- }
42
-
43
- main();