@haustle/notion-orm 0.0.2 → 0.0.4

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 (32) hide show
  1. package/build/src/BuildCall.d.ts +32 -0
  2. package/build/src/BuildCall.d.ts.map +1 -0
  3. package/build/{NotionActions → src}/BuildCall.js +1 -0
  4. package/build/src/BuildCall.js.map +1 -0
  5. package/build/src/DatabaseActions.d.ts +17 -0
  6. package/build/src/DatabaseActions.d.ts.map +1 -0
  7. package/build/{NotionActions/NotionCollection.js → src/DatabaseActions.js} +11 -5
  8. package/build/src/DatabaseActions.js.map +1 -0
  9. package/build/src/GenerateTypes.d.ts +10 -0
  10. package/build/src/GenerateTypes.d.ts.map +1 -0
  11. package/build/{NotionActions → src}/GenerateTypes.js +56 -57
  12. package/build/src/GenerateTypes.js.map +1 -0
  13. package/build/src/NotionConfig.d.ts +9 -0
  14. package/build/src/NotionConfig.d.ts.map +1 -0
  15. package/build/{NotionActions → src}/NotionConfig.js +37 -40
  16. package/build/src/NotionConfig.js.map +1 -0
  17. package/build/src/cli.d.ts +3 -0
  18. package/build/src/cli.d.ts.map +1 -0
  19. package/build/{index.js → src/cli.js} +2 -2
  20. package/build/src/cli.js.map +1 -0
  21. package/build/src/queryTypes.d.ts +102 -0
  22. package/build/src/queryTypes.d.ts.map +1 -0
  23. package/build/{NotionActions → src}/queryTypes.js +1 -0
  24. package/build/src/queryTypes.js.map +1 -0
  25. package/package.json +7 -13
  26. package/src/NotionActions/BuildCall.ts +0 -85
  27. package/src/NotionActions/GenerateTypes.ts +0 -417
  28. package/src/NotionActions/NotionCollection.ts +0 -126
  29. package/src/NotionActions/NotionConfig.ts +0 -150
  30. package/src/NotionActions/queryTypes.ts +0 -141
  31. package/src/index.ts +0 -43
  32. package/tsconfig.json +0 -22
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queryTypes.d.ts","sourceRoot":"","sources":["../../src/queryTypes.ts"],"names":[],"mappings":"AAA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IAAI,CAAC,EAAE,EAAE,CAAC;CACV,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC5B,MAAM,CAAC,EAAE,eAAe,GAAG,YAAY,GAAG,WAAW,CAAC;CACtD,CAAC;AAEF;;;GAGG;AAEH,KAAK,sBAAsB,GAAG;KAC5B,IAAI,IAAI,MAAM,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;CAC5D,CAAC;AACF,MAAM,WAAW,eAAgB,SAAQ,sBAAsB;IAC9D,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,MAAM,aAAa,GACtB,eAAe,GACf,YAAY,GACZ,WAAW,GACX,SAAS,CAAC;AACb,KAAK,YAAY,GAAG;IACnB,GAAG,EAAE,KAAK,CAAC,aAAa,CAAC,CAAC;CAC1B,CAAC;AAEF,KAAK,WAAW,GAAG;IAClB,EAAE,EAAE,KAAK,CAAC,aAAa,CAAC,CAAC;CACzB,CAAC"}
@@ -10,3 +10,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
10
10
  const x = {
11
11
  character: "multi_select",
12
12
  };
13
+ //# sourceMappingURL=queryTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queryTypes.js","sourceRoot":"","sources":["../../src/queryTypes.ts"],"names":[],"mappings":";AAAA;;GAEG;AACH,gCAAgC;;AAyFhC;;GAEG;AAEH,MAAM,CAAC,GAAG;IACT,SAAS,EAAE,cAAc;CACzB,CAAC"}
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@haustle/notion-orm",
3
- "version": "0.0.2",
4
- "description": "tool to bring collection types to typescript",
5
- "main": "build/index.js",
3
+ "version": "0.0.4",
4
+ "description": "tool to bring notion databases schemas/types to typescript",
5
+ "main": "build/databases/index.js",
6
6
  "bin": {
7
- "notion": "build/index.js"
7
+ "notion": "build/src/cli.js"
8
8
  },
9
9
  "scripts": {
10
- "start": "npx tsc && node build/index.js",
11
- "build": "tsc -p .",
10
+ "start": "npx tsc && node build/src/index.js",
11
+ "build": "rm -rf build && tsc",
12
12
  "test": "echo \"Error: no test specified\" && exit 1",
13
13
  "refresh": "rm -rf ./node_modules ./package-lock.json && npm install"
14
14
  },
@@ -19,12 +19,6 @@
19
19
  "typescript": "^4.8.4"
20
20
  },
21
21
  "dependencies": {
22
- "@notionhq/client": "^2.2.2",
23
- "dotenv": "^16.0.3",
24
- "module-alias": "^2.2.2",
25
- "path": "^0.12.7"
26
- },
27
- "_moduleAliases": {
28
- "@notion-database": "build/NotionActions/DatabaseTypes"
22
+ "@notionhq/client": "^2.2.2"
29
23
  }
30
24
  }
@@ -1,85 +0,0 @@
1
- import { PropertyType } from "./GenerateTypes";
2
-
3
- export function getCall(args: {
4
- type: PropertyType;
5
- value: string | number | boolean;
6
- }) {
7
- const { type, value } = args;
8
- console.log(type, value, typeof value);
9
- if (type === "select" && typeof value === "string") {
10
- return selectCall({ value });
11
- } else if (type === "multi_select" && Array.isArray(value)) {
12
- return multiSelectCall({ value });
13
- } else if (type === "number" && typeof value === "number") {
14
- return numberCall({ value });
15
- } else if (type === "url" && typeof value === "string") {
16
- return urlCall({ url: value });
17
- } else if (type === "checkbox" && typeof value === "boolean") {
18
- return checkboxCall({ checked: value });
19
- } else if (type === "title" && typeof value === "string") {
20
- return titleCall({ title: value });
21
- } else if (type === "text" && typeof value === "string") {
22
- return textCall({ text: value });
23
- }
24
- }
25
-
26
- /*
27
- ======================================================
28
- GENERATE OBJECT BASED ON TYPE
29
- ======================================================
30
- */
31
-
32
- const selectCall = (args: { value: string }) => {
33
- const { value } = args;
34
- const select = {
35
- name: value,
36
- };
37
- return { select };
38
- };
39
-
40
- const multiSelectCall = (args: { value: Array<string> }) => {
41
- const { value } = args;
42
- const multi_select = value.map((option) => ({ name: option }));
43
- return { multi_select };
44
- };
45
-
46
- const textCall = (args: { text: string }) => {
47
- const { text } = args;
48
- const rich_text = [
49
- {
50
- text: {
51
- content: text,
52
- },
53
- },
54
- ];
55
-
56
- return { rich_text };
57
- };
58
-
59
- const titleCall = (args: { title: string }) => {
60
- const { title } = args;
61
- const titleObject = [
62
- {
63
- text: {
64
- content: title,
65
- },
66
- },
67
- ];
68
-
69
- return { title: titleObject };
70
- };
71
-
72
- const numberCall = (args: { value: number }) => {
73
- const { value: number } = args;
74
- return { number };
75
- };
76
-
77
- const urlCall = (args: { url: string }) => {
78
- const { url } = args;
79
- return { url };
80
- };
81
-
82
- const checkboxCall = (args: { checked: boolean }) => {
83
- const { checked: checkbox } = args;
84
- return { checkbox };
85
- };
@@ -1,417 +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
-
9
- // This can be grabbed from // api-endpoints.d.ts with some work
10
- const propertyArr = [
11
- "text",
12
- "select",
13
- "title",
14
- "number",
15
- "multi_select",
16
- "checkbox",
17
- "url",
18
- ];
19
- export type PropertyType = typeof propertyArr[number];
20
-
21
- type propNameToColumnNameType = Record<
22
- string,
23
- { columnName: string; type: PropertyType }
24
- >;
25
-
26
- /*
27
- Responsible for generating `.ts` files
28
- */
29
- export async function createTypescriptFileForDatabase(
30
- dbResponse: GetDatabaseResponse
31
- ) {
32
- const {
33
- id: databaseId,
34
- properties,
35
- title,
36
- } = dbResponse as DatabaseObjectResponse;
37
- const propNameToColumnName: propNameToColumnNameType = {};
38
- const databaseName = title[0].plain_text;
39
- const databaseClassName = camelize(databaseName).replace(/[^a-zA-Z0-9]/g, "");
40
-
41
- const databaseColumnTypeProps: ts.TypeElement[] = [];
42
-
43
- // Looping through each column of database
44
- Object.values(properties).forEach((value) => {
45
- const { type: columnType, name: columnName } = value;
46
-
47
- // Taking the column name and camelizing it for typescript use
48
- const camelizedColumnName = camelize(columnName);
49
-
50
- // Creating map of column name to the column's name in the database's typescript type
51
- propNameToColumnName[camelizedColumnName] = {
52
- columnName,
53
- type: columnType,
54
- };
55
-
56
- if (columnType === "title" || columnType === "rich_text") {
57
- // add text column to collection type
58
- databaseColumnTypeProps.push(
59
- createTextProperty(camelizedColumnName, columnType === "title")
60
- );
61
- } else if (columnType === "number") {
62
- // add number column to collection type
63
- databaseColumnTypeProps.push(createNumberProperty(camelizedColumnName));
64
- } else if (columnType === "url") {
65
- // add url column to collection type
66
- databaseColumnTypeProps.push(
67
- createTextProperty(camelizedColumnName, false)
68
- );
69
- } else if (columnType === "date") {
70
- // add Date column to collection type
71
- databaseColumnTypeProps.push(createDateProperty(camelizedColumnName));
72
- } else if (columnType == "select" || columnType == "multi_select") {
73
- // @ts-ignore
74
- const options = value[columnType].options.map((x) => x.name);
75
- databaseColumnTypeProps.push(
76
- createMultiOptionProp(
77
- camelizedColumnName,
78
- options,
79
- // This determines whether the property needs to be a union or a union array
80
- columnType === "multi_select"
81
- )
82
- );
83
- }
84
- });
85
-
86
- // Object type that represents the database schema
87
- const CollectionType = ts.factory.createTypeAliasDeclaration(
88
- [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
89
- ts.factory.createIdentifier("CollectionType"),
90
- undefined,
91
- ts.factory.createTypeLiteralNode(databaseColumnTypeProps)
92
- );
93
-
94
- // Top level non-nested variable, functions, types
95
- const nodeArr = [
96
- importCollectionClass(),
97
- createDatabaseIdVariable(databaseId),
98
- CollectionType,
99
- mapPropNameToColumnDetails(propNameToColumnName),
100
- ColNameToType(),
101
- exportCollectionActions(databaseClassName),
102
- ];
103
-
104
- const nodes = ts.factory.createNodeArray(nodeArr);
105
-
106
- const sourceFile = ts.createSourceFile(
107
- "placeholder.ts",
108
- "",
109
- ts.ScriptTarget.ESNext,
110
- true,
111
- ts.ScriptKind.TS
112
- );
113
- const printer = ts.createPrinter();
114
-
115
- const outputFile = printer.printList(
116
- ts.ListFormat.MultiLine,
117
- nodes,
118
- sourceFile
119
- );
120
-
121
- // Create our output folder
122
- const outputDir = path.join(
123
- __dirname,
124
- "../../src",
125
- "NotionActions",
126
- "DatabaseTypes"
127
- );
128
- if (!fs.existsSync(outputDir)) {
129
- fs.mkdirSync(outputDir);
130
- }
131
- fs.writeFileSync(path.resolve(outputDir, `${databaseId}.ts`), outputFile);
132
-
133
- return { databaseName, databaseClassName, databaseId };
134
- }
135
-
136
- // generate text property
137
- function createTextProperty(name: string, isTitle: boolean) {
138
- const text = ts.factory.createPropertySignature(
139
- undefined,
140
- ts.factory.createIdentifier(name),
141
- !isTitle ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined,
142
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)
143
- );
144
- return text;
145
- }
146
-
147
- /**
148
- * Generate number property to go inside a type
149
- * name: number
150
- */
151
- function createNumberProperty(name: string) {
152
- const number = ts.factory.createPropertySignature(
153
- undefined,
154
- ts.factory.createIdentifier(name),
155
- ts.factory.createToken(ts.SyntaxKind.QuestionToken),
156
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword)
157
- );
158
- return number;
159
- }
160
-
161
- /**
162
- *
163
- * @param name name of property
164
- * @param options
165
- * @param array
166
- * @returns
167
- *
168
- * For selects and multi-select collection properties
169
- *
170
- * array = true for multi-select
171
- *
172
- * name = ("x" | "y" | "z")[]
173
- */
174
- function createMultiOptionProp(
175
- name: string,
176
- options: string[],
177
- array: boolean
178
- ) {
179
- return ts.factory.createPropertySignature(
180
- undefined,
181
- ts.factory.createIdentifier(name),
182
- ts.factory.createToken(ts.SyntaxKind.QuestionToken),
183
- array
184
- ? ts.factory.createArrayTypeNode(
185
- ts.factory.createParenthesizedType(
186
- ts.factory.createUnionTypeNode([
187
- ...options.map((option) =>
188
- ts.factory.createLiteralTypeNode(
189
- ts.factory.createStringLiteral(option)
190
- )
191
- ),
192
- createOtherStringProp(),
193
- ])
194
- )
195
- )
196
- : ts.factory.createUnionTypeNode([
197
- ...options.map((option) =>
198
- ts.factory.createLiteralTypeNode(
199
- ts.factory.createStringLiteral(option)
200
- )
201
- ),
202
- createOtherStringProp(),
203
- ])
204
- );
205
- }
206
-
207
- // string & {}. Allows users to pass in values
208
- function createOtherStringProp() {
209
- return ts.factory.createIntersectionTypeNode([
210
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
211
- ts.factory.createTypeLiteralNode([]),
212
- ]);
213
- }
214
- function createDateProperty(name: string) {
215
- return ts.factory.createPropertySignature(
216
- undefined,
217
- ts.factory.createIdentifier("s"),
218
- undefined,
219
- ts.factory.createTypeReferenceNode(
220
- ts.factory.createIdentifier("Date"),
221
- undefined
222
- )
223
- );
224
- }
225
-
226
- // Generate database Id variable
227
- // const databaseId = <database-id>
228
- function createDatabaseIdVariable(databaseId: string) {
229
- return ts.factory.createVariableStatement(
230
- undefined,
231
- ts.factory.createVariableDeclarationList(
232
- [
233
- ts.factory.createVariableDeclaration(
234
- ts.factory.createIdentifier("databaseId"),
235
- undefined,
236
- undefined,
237
- ts.factory.createStringLiteral(databaseId)
238
- ),
239
- ],
240
- ts.NodeFlags.Const
241
- )
242
- );
243
- }
244
-
245
- /**
246
- * Instead of refering to the column names 1:1 such as "Book Rating", we transform them to
247
- * camelcase (eg. bookRating). So we need to keep track of the original name and the type
248
- * for when we construct request for API
249
- *
250
- * Example
251
- *
252
- * const propMap = {
253
- *
254
- * "bookRating": {
255
- * columnName: "Book Rating",
256
- * type: "select"
257
- * },
258
- * "genre": {
259
- * columnName: "Genre",
260
- * type: "multi_select"
261
- * }
262
- *
263
- * }
264
- * @param colMap
265
- * @returns
266
- */
267
- function mapPropNameToColumnDetails(colMap: propNameToColumnNameType) {
268
- return ts.factory.createVariableDeclarationList(
269
- [
270
- ts.factory.createVariableDeclaration(
271
- ts.factory.createIdentifier("propMap"),
272
- undefined,
273
- undefined,
274
- ts.factory.createAsExpression(
275
- ts.factory.createObjectLiteralExpression(
276
- [
277
- ...Object.entries(colMap).map(([propName, value]) =>
278
- ts.factory.createPropertyAssignment(
279
- ts.factory.createStringLiteral(propName),
280
- ts.factory.createObjectLiteralExpression(
281
- [
282
- ts.factory.createPropertyAssignment(
283
- ts.factory.createIdentifier("columnName"),
284
- ts.factory.createStringLiteral(value.columnName)
285
- ),
286
- ts.factory.createPropertyAssignment(
287
- ts.factory.createIdentifier("type"),
288
- ts.factory.createStringLiteral(value.type)
289
- ),
290
- ],
291
- true
292
- )
293
- )
294
- ),
295
- ],
296
- true
297
- ),
298
- ts.factory.createTypeReferenceNode(
299
- ts.factory.createIdentifier("const"),
300
- undefined
301
- )
302
- )
303
- ),
304
- ],
305
- ts.NodeFlags.Const
306
- );
307
- }
308
-
309
- function ColNameToType() {
310
- return ts.factory.createTypeAliasDeclaration(
311
- undefined,
312
- ts.factory.createIdentifier("ColNameToType"),
313
- undefined,
314
- ts.factory.createMappedTypeNode(
315
- undefined,
316
- ts.factory.createTypeParameterDeclaration(
317
- undefined,
318
- ts.factory.createIdentifier("Property"),
319
- ts.factory.createTypeOperatorNode(
320
- ts.SyntaxKind.KeyOfKeyword,
321
- ts.factory.createTypeQueryNode(
322
- ts.factory.createIdentifier("propMap"),
323
- undefined
324
- )
325
- ),
326
- undefined
327
- ),
328
- undefined,
329
- undefined,
330
- ts.factory.createIndexedAccessTypeNode(
331
- ts.factory.createIndexedAccessTypeNode(
332
- ts.factory.createTypeQueryNode(
333
- ts.factory.createIdentifier("propMap"),
334
- undefined
335
- ),
336
- ts.factory.createTypeReferenceNode(
337
- ts.factory.createIdentifier("Property"),
338
- undefined
339
- )
340
- ),
341
- ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral("type"))
342
- ),
343
- undefined
344
- /* unknown */
345
- )
346
- );
347
- }
348
-
349
- // Need to import the class responsible for adding and querying the database
350
- function importCollectionClass() {
351
- return ts.factory.createImportDeclaration(
352
- undefined,
353
- ts.factory.createImportClause(
354
- false,
355
- undefined,
356
- ts.factory.createNamedImports([
357
- ts.factory.createImportSpecifier(
358
- false,
359
- undefined,
360
- ts.factory.createIdentifier("CollectionActions")
361
- ),
362
- ])
363
- ),
364
- ts.factory.createStringLiteral("../NotionCollection"),
365
- undefined
366
- );
367
- }
368
-
369
- // We export the database with the class above.
370
- // export
371
-
372
- /**
373
- * We export the database with
374
- * @param databaseName
375
- *
376
- * const <datbase-name> = new CollectionActions<CollectionType>(datbaseId, propMap)
377
- */
378
- function exportCollectionActions(databaseName: string) {
379
- return ts.factory.createVariableStatement(
380
- [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
381
- ts.factory.createVariableDeclarationList(
382
- [
383
- ts.factory.createVariableDeclaration(
384
- ts.factory.createIdentifier(databaseName),
385
- undefined,
386
- undefined,
387
- ts.factory.createNewExpression(
388
- ts.factory.createIdentifier("CollectionActions"),
389
- [
390
- ts.factory.createTypeReferenceNode(
391
- ts.factory.createIdentifier("CollectionType"),
392
- undefined
393
- ),
394
- ts.factory.createTypeReferenceNode(
395
- ts.factory.createIdentifier("ColNameToType"),
396
- undefined
397
- ),
398
- ],
399
- [
400
- ts.factory.createIdentifier("databaseId"),
401
- ts.factory.createIdentifier("propMap"),
402
- ]
403
- )
404
- ),
405
- ],
406
- ts.NodeFlags.Const
407
- )
408
- );
409
- }
410
-
411
- // for a type's property name
412
- function camelize(str: string) {
413
- return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {
414
- if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
415
- return index === 0 ? match.toLowerCase() : match.toUpperCase();
416
- });
417
- }
@@ -1,126 +0,0 @@
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 { PropertyType } from "./GenerateTypes";
8
- import {
9
- apiFilterType,
10
- apiSingleFilter,
11
- CompoundFilters,
12
- FilterOptionNames,
13
- Query,
14
- QueryFilter,
15
- SingleFilter,
16
- } from "./queryTypes";
17
- require("dotenv").config();
18
-
19
- export type propNameToColumnNameType = Record<
20
- string,
21
- { columnName: string; type: PropertyType }
22
- >;
23
-
24
- export class CollectionActions<
25
- CollectionType extends Record<string, any>,
26
- ColNameToType extends Record<keyof CollectionType, FilterOptionNames>
27
- > {
28
- private NotionClient: Client = new Client({
29
- auth: process.env.NOTION_KEY,
30
- });
31
- private databaseId: string;
32
- private propNameToColumnName: propNameToColumnNameType;
33
- private columnNames: string[];
34
-
35
- constructor(
36
- datbaseId: string,
37
- propNameToColumnName: propNameToColumnNameType
38
- ) {
39
- this.databaseId = datbaseId;
40
- this.propNameToColumnName = propNameToColumnName;
41
- this.columnNames = Object.keys(propNameToColumnName);
42
- }
43
-
44
- // Add page to a database
45
- async add(pageObject: CollectionType) {
46
- const callBody: CreatePageParameters = {
47
- parent: {
48
- database_id: this.databaseId,
49
- },
50
- properties: {},
51
- };
52
-
53
- const columnTypePropNames = Object.keys(pageObject);
54
- columnTypePropNames.forEach((propName) => {
55
- const { type, columnName } = this.propNameToColumnName[propName];
56
- const columnObject = getCall({
57
- type,
58
- value: pageObject[propName],
59
- });
60
-
61
- callBody.properties[columnName] = columnObject!;
62
- });
63
-
64
- // console.log(JSON.stringify(callBody, null, 4));
65
- await this.NotionClient.pages.create(callBody);
66
- }
67
-
68
- // Look for page inside the database
69
- async query(query: Query<CollectionType, ColNameToType>) {
70
- const queryCall: QueryDatabaseParameters = {
71
- database_id: this.databaseId,
72
- };
73
-
74
- const filters = query.filter
75
- ? this.recursivelyBuildFilter(query.filter)
76
- : undefined;
77
- if (filters) {
78
- // @ts-ignore errors vs notion api types
79
- queryCall["filter"] = filters;
80
- }
81
-
82
- console.log(JSON.stringify(queryCall, null, 4));
83
-
84
- const sort = query.sort;
85
-
86
- const apiQuery = await this.NotionClient.databases.query(queryCall);
87
- console.log(apiQuery);
88
- }
89
-
90
- private recursivelyBuildFilter(
91
- queryFilter: QueryFilter<CollectionType, ColNameToType>
92
- ): apiFilterType {
93
- // Need to loop because we don't kno
94
- for (const prop in queryFilter) {
95
- // if the filter is "and" || "or" we need to recursively
96
- if (prop === "and" || prop === "or") {
97
- const compoundFilters: QueryFilter<CollectionType, ColNameToType>[] =
98
- // @ts-ignore
99
- queryFilter[prop];
100
-
101
- const compoundApiFilters = compoundFilters.map(
102
- (i: QueryFilter<CollectionType, ColNameToType>) => {
103
- return this.recursivelyBuildFilter(i);
104
- }
105
- );
106
-
107
- // Either have an `and` or an `or` compound filter
108
- let temp: apiFilterType = {
109
- ...(prop === "and"
110
- ? { and: compoundApiFilters }
111
- : { or: compoundApiFilters }),
112
- };
113
- return temp;
114
- } else {
115
- const propType = this.propNameToColumnName[prop].type;
116
- const temp: apiSingleFilter = {
117
- property: this.propNameToColumnName[prop].columnName,
118
- };
119
-
120
- //@ts-ignore
121
- temp[propType] = (queryFilter as SingleFilter<ColNameToType>)[prop];
122
- return temp;
123
- }
124
- }
125
- }
126
- }