inibase 1.0.0-rc.9 → 1.0.0-rc.90

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/index.ts DELETED
@@ -1,1488 +0,0 @@
1
- import {
2
- unlink,
3
- rename,
4
- readFile,
5
- writeFile,
6
- appendFile,
7
- mkdir,
8
- readdir,
9
- } from "node:fs/promises";
10
- import { join, parse } from "node:path";
11
- import { scryptSync } from "node:crypto";
12
- import File from "./file";
13
- import Utils from "./utils";
14
- import UtilsServer from "./utils.server";
15
-
16
- export type Data = {
17
- id?: number | string;
18
- [key: string]: any;
19
- created_at?: Date;
20
- updated_at?: Date;
21
- };
22
-
23
- export type FieldType =
24
- | "string"
25
- | "number"
26
- | "boolean"
27
- | "date"
28
- | "email"
29
- | "url"
30
- | "table"
31
- | "object"
32
- | "array"
33
- | "password"
34
- | "html"
35
- | "ip"
36
- | "id";
37
- type FieldDefault = {
38
- id?: string | number | null | undefined;
39
- key: string;
40
- required?: boolean;
41
- children?: any;
42
- };
43
- type FieldStringType = {
44
- type: Exclude<FieldType, "array" | "object">;
45
- };
46
- type FieldStringArrayType = {
47
- type: Exclude<FieldType, "array" | "object">[];
48
- };
49
- type FieldArrayType = {
50
- type: "array";
51
- children: FieldType | FieldType[] | Schema;
52
- };
53
- type FieldArrayArrayType = {
54
- type: ["array", ...FieldType[]];
55
- children: FieldType | FieldType[];
56
- };
57
- type FieldObjectType = {
58
- type: "object";
59
- children: Schema;
60
- };
61
- // if "type" is array, make "array" at first place, and "number" & "string" at last place of the array
62
- export type Field = FieldDefault &
63
- (
64
- | FieldStringType
65
- | FieldStringArrayType
66
- | FieldObjectType
67
- | FieldArrayType
68
- | FieldArrayArrayType
69
- );
70
-
71
- export type Schema = Field[];
72
-
73
- export interface Options {
74
- page?: number;
75
- per_page?: number;
76
- columns?: string[] | string;
77
- }
78
-
79
- export type ComparisonOperator =
80
- | "="
81
- | "!="
82
- | ">"
83
- | "<"
84
- | ">="
85
- | "<="
86
- | "*"
87
- | "!*"
88
- | "[]"
89
- | "![]";
90
-
91
- type pageInfo = {
92
- total?: number;
93
- total_pages?: number;
94
- } & Options;
95
-
96
- export type Criteria =
97
- | {
98
- [logic in "and" | "or"]?: Criteria | (string | number | boolean | null)[];
99
- }
100
- | {
101
- [key: string]: string | number | boolean | Criteria;
102
- }
103
- | null;
104
-
105
- declare global {
106
- type Entries<T> = {
107
- [K in keyof T]: [K, T[K]];
108
- }[keyof T][];
109
-
110
- interface ObjectConstructor {
111
- entries<T extends object>(o: T): Entries<T>;
112
- }
113
- }
114
-
115
- export default class Inibase {
116
- public folder: string;
117
- public database: string;
118
- public table: string;
119
- public pageInfo: pageInfo;
120
- private cache: Map<string, string>;
121
- private totalItems: Record<string, number>;
122
- private salt: Buffer;
123
-
124
- constructor(database: string, mainFolder: string = ".") {
125
- this.database = database;
126
- this.folder = mainFolder;
127
- this.table = null;
128
- this.cache = new Map<string, any>();
129
- this.totalItems = {};
130
- this.pageInfo = { page: 1, per_page: 15 };
131
- this.salt = scryptSync(database, "salt", 32);
132
- }
133
-
134
- private throwError(
135
- code: string,
136
- variable?:
137
- | string
138
- | number
139
- | (string | number)[]
140
- | Record<string, string | number>,
141
- language: string = "en"
142
- ): Error {
143
- const errorMessages: Record<string, Record<string, string>> = {
144
- en: {
145
- FIELD_REQUIRED: "REQUIRED: {variable}",
146
- NO_SCHEMA: "NO_SCHEMA: {variable}",
147
- NO_ITEMS: "NO_ITEMS: {variable}",
148
- NO_DATA: "NO_DATA: {variable}",
149
- INVALID_ID: "INVALID_ID: {variable}",
150
- INVALID_TYPE: "INVALID_TYPE: {variable}",
151
- INVALID_OPERATOR: "INVALID_OPERATOR: {variable}",
152
- INVALID_PARAMETERS: "PARAMETERS: {variable}",
153
- },
154
- // Add more languages and error messages as needed
155
- };
156
-
157
- let errorMessage = errorMessages[language][code] || code;
158
- if (variable) {
159
- if (
160
- typeof variable === "string" ||
161
- typeof variable === "number" ||
162
- Array.isArray(variable)
163
- )
164
- errorMessage = errorMessage.replaceAll(
165
- `{variable}`,
166
- Array.isArray(variable) ? variable.join(", ") : (variable as string)
167
- );
168
- else
169
- Object.keys(variable).forEach(
170
- (variableKey) =>
171
- (errorMessage = errorMessage.replaceAll(
172
- `{${variableKey}}`,
173
- variable[variableKey].toString()
174
- ))
175
- );
176
- }
177
- return new Error(errorMessage);
178
- }
179
-
180
- private findLastIdNumber(schema: Schema): number {
181
- const lastField = schema[schema.length - 1];
182
- if (lastField) {
183
- if (
184
- (lastField.type === "array" || lastField.type === "object") &&
185
- Utils.isArrayOfObjects(lastField.children)
186
- )
187
- return this.findLastIdNumber(lastField.children as Schema);
188
- else if (lastField.id && Utils.isValidID(lastField.id))
189
- return UtilsServer.decodeID(lastField.id as string, this.salt);
190
- }
191
- return 0;
192
- }
193
-
194
- public async setTableSchema(
195
- tableName: string,
196
- schema: Schema
197
- ): Promise<void> {
198
- const encodeSchema = (schema: Schema) => {
199
- let RETURN: any[][] = [],
200
- index = 0;
201
- for (const field of schema) {
202
- if (!RETURN[index]) RETURN[index] = [];
203
- RETURN[index].push(
204
- field.id
205
- ? UtilsServer.decodeID(field.id as string, this.salt)
206
- : null
207
- );
208
- RETURN[index].push(field.key ?? null);
209
- RETURN[index].push(field.required ?? null);
210
- RETURN[index].push(field.type ?? null);
211
- RETURN[index].push(
212
- (field as any).children
213
- ? Utils.isArrayOfObjects((field as any).children)
214
- ? encodeSchema((field as any).children as Schema) ?? null
215
- : (field as any).children
216
- : null
217
- );
218
- index++;
219
- }
220
- return RETURN;
221
- },
222
- addIdToSchema = (schema: Schema, oldIndex: number = 0) =>
223
- schema.map((field) => {
224
- if (
225
- (field.type === "array" || field.type === "object") &&
226
- Utils.isArrayOfObjects(field.children)
227
- ) {
228
- if (!field.id) {
229
- oldIndex++;
230
- field = {
231
- ...field,
232
- id: UtilsServer.encodeID(oldIndex, this.salt),
233
- };
234
- } else
235
- oldIndex = UtilsServer.decodeID(field.id as string, this.salt);
236
- field.children = addIdToSchema(field.children as Schema, oldIndex);
237
- oldIndex += field.children.length;
238
- } else if (field.id)
239
- oldIndex = UtilsServer.decodeID(field.id as string, this.salt);
240
- else {
241
- oldIndex++;
242
- field = {
243
- ...field,
244
- id: UtilsServer.encodeID(oldIndex, this.salt),
245
- };
246
- }
247
- return field;
248
- });
249
-
250
- // remove id from schema
251
- schema = schema.filter(
252
- (field) => !["id", "created_at", "updated_at"].includes(field.key)
253
- );
254
- schema = addIdToSchema(schema, this.findLastIdNumber(schema));
255
- const TablePath = join(this.folder, this.database, tableName),
256
- TableSchemaPath = join(TablePath, "schema");
257
- if (!(await File.isExists(TablePath)))
258
- await mkdir(TablePath, { recursive: true });
259
- if (await File.isExists(TableSchemaPath)) {
260
- // update columns files names based on field id
261
- const schemaToIdsPath = (schema: any, prefix = "") => {
262
- let RETURN: any = {};
263
- for (const field of schema)
264
- if (field.children && Utils.isArrayOfObjects(field.children)) {
265
- Utils.deepMerge(
266
- RETURN,
267
- schemaToIdsPath(
268
- field.children,
269
- (prefix ?? "") + field.key + "."
270
- )
271
- );
272
- } else if (Utils.isValidID(field.id))
273
- RETURN[UtilsServer.decodeID(field.id, this.salt)] =
274
- (prefix ?? "") + field.key + ".inib";
275
-
276
- return RETURN;
277
- },
278
- replaceOldPathes = Utils.findChangedProperties(
279
- schemaToIdsPath(await this.getTableSchema(tableName)),
280
- schemaToIdsPath(schema)
281
- );
282
- if (replaceOldPathes)
283
- for (const [oldPath, newPath] of Object.entries(replaceOldPathes))
284
- if (await File.isExists(join(TablePath, oldPath)))
285
- await rename(join(TablePath, oldPath), join(TablePath, newPath));
286
- }
287
-
288
- await writeFile(
289
- join(TablePath, "schema"),
290
- JSON.stringify(encodeSchema(schema))
291
- );
292
- }
293
-
294
- public async getTableSchema(tableName: string): Promise<Schema | undefined> {
295
- const decodeSchema = (encodedSchema: any) => {
296
- return encodedSchema.map((field: any) =>
297
- Array.isArray(field[0])
298
- ? decodeSchema(field)
299
- : Object.fromEntries(
300
- Object.entries({
301
- id: UtilsServer.encodeID(field[0], this.salt),
302
- key: field[1],
303
- required: field[2],
304
- type: field[3],
305
- children: field[4]
306
- ? Array.isArray(field[4])
307
- ? decodeSchema(field[4])
308
- : field[4]
309
- : null,
310
- }).filter(([_, v]) => v != null)
311
- )
312
- );
313
- },
314
- TableSchemaPath = join(this.folder, this.database, tableName, "schema");
315
- if (!(await File.isExists(TableSchemaPath))) return undefined;
316
- if (!this.cache.has(TableSchemaPath)) {
317
- const TableSchemaPathContent = await readFile(TableSchemaPath, {
318
- encoding: "utf8",
319
- });
320
- this.cache.set(
321
- TableSchemaPath,
322
- TableSchemaPathContent
323
- ? decodeSchema(JSON.parse(TableSchemaPathContent.toString()))
324
- : ""
325
- );
326
- }
327
- const schema = this.cache.get(TableSchemaPath) as unknown as Schema,
328
- lastIdNumber = this.findLastIdNumber(schema);
329
- return [
330
- {
331
- id: UtilsServer.encodeID(0, this.salt),
332
- key: "id",
333
- type: "id",
334
- required: true,
335
- },
336
- ...schema,
337
- {
338
- id: UtilsServer.encodeID(lastIdNumber + 1, this.salt),
339
- key: "created_at",
340
- type: "date",
341
- required: true,
342
- },
343
- {
344
- id: UtilsServer.encodeID(lastIdNumber + 2, this.salt),
345
- key: "updated_at",
346
- type: "date",
347
- required: false,
348
- },
349
- ];
350
- }
351
-
352
- public getField<Property extends keyof Field | "children">(
353
- keyPath: string,
354
- schema: Schema | Field,
355
- property?: Property
356
- ) {
357
- const keyPathSplited = keyPath.split(".");
358
- for (const [index, key] of keyPathSplited.entries()) {
359
- if (key === "*") continue;
360
- const foundItem = (schema as Schema).find((item) => item.key === key);
361
- if (!foundItem) return null;
362
- if (index === keyPathSplited.length - 1) schema = foundItem;
363
- if (
364
- (foundItem.type === "array" || foundItem.type === "object") &&
365
- foundItem.children &&
366
- Utils.isArrayOfObjects(foundItem.children)
367
- )
368
- schema = foundItem.children as Schema;
369
- }
370
- if (property) {
371
- switch (property) {
372
- case "type":
373
- return (schema as Field).type;
374
- case "children":
375
- return (
376
- schema as
377
- | (Field & FieldObjectType)
378
- | FieldArrayType
379
- | FieldArrayArrayType
380
- ).children;
381
-
382
- default:
383
- return (schema as Field)[property as keyof Field];
384
- }
385
- } else return schema as Field;
386
- }
387
-
388
- public validateData(
389
- data: Data | Data[],
390
- schema: Schema,
391
- skipRequiredField: boolean = false
392
- ): void {
393
- if (Utils.isArrayOfObjects(data))
394
- for (const single_data of data as Data[])
395
- this.validateData(single_data, schema, skipRequiredField);
396
- else if (Utils.isObject(data)) {
397
- for (const field of schema) {
398
- if (
399
- !data.hasOwnProperty(field.key) &&
400
- field.required &&
401
- !skipRequiredField
402
- )
403
- throw this.throwError("FIELD_REQUIRED", field.key);
404
- if (
405
- data.hasOwnProperty(field.key) &&
406
- !Utils.validateFieldType(
407
- data[field.key],
408
- field.type,
409
- (field as any)?.children &&
410
- !Utils.isArrayOfObjects((field as any)?.children)
411
- ? (field as any)?.children
412
- : undefined
413
- )
414
- )
415
- throw this.throwError("INVALID_TYPE", field.key);
416
- if (
417
- (field.type === "array" || field.type === "object") &&
418
- field.children &&
419
- Utils.isArrayOfObjects(field.children)
420
- )
421
- this.validateData(
422
- data[field.key],
423
- field.children as Schema,
424
- skipRequiredField
425
- );
426
- }
427
- }
428
- }
429
-
430
- public formatData(
431
- data: Data | Data[],
432
- schema: Schema,
433
- formatOnlyAvailiableKeys?: boolean
434
- ): Data | Data[] {
435
- const formatField = (
436
- value: any,
437
- field: Field
438
- ): Data | Data[] | number | string => {
439
- if (Array.isArray(field.type))
440
- field.type = Utils.detectFieldType(value, field.type);
441
- switch (field.type) {
442
- case "array":
443
- if (typeof field.children === "string") {
444
- if (field.type === "array" && field.children === "table") {
445
- if (Array.isArray(data[field.key])) {
446
- if (Utils.isArrayOfObjects(data[field.key])) {
447
- if (
448
- value.every(
449
- (item: any) =>
450
- item.hasOwnProperty("id") &&
451
- (Utils.isValidID(item.id) || Utils.isNumber(item.id))
452
- )
453
- )
454
- value.map((item: any) =>
455
- Utils.isNumber(item.id)
456
- ? Number(item.id)
457
- : UtilsServer.decodeID(item.id, this.salt)
458
- );
459
- } else if (Utils.isValidID(value) || Utils.isNumber(value))
460
- return value.map((item: number | string) =>
461
- Utils.isNumber(item)
462
- ? Number(item as string)
463
- : UtilsServer.decodeID(item as string, this.salt)
464
- );
465
- } else if (Utils.isValidID(value))
466
- return [UtilsServer.decodeID(value, this.salt)];
467
- else if (Utils.isNumber(value)) return [Number(value)];
468
- } else if (data.hasOwnProperty(field.key)) return value;
469
- } else if (Utils.isArrayOfObjects(field.children))
470
- return this.formatData(
471
- value,
472
- field.children as Schema,
473
- formatOnlyAvailiableKeys
474
- );
475
- else if (Array.isArray(field.children))
476
- return Array.isArray(value) ? value : [value];
477
- break;
478
- case "object":
479
- if (Utils.isArrayOfObjects(field.children))
480
- return this.formatData(
481
- value,
482
- field.children,
483
- formatOnlyAvailiableKeys
484
- );
485
- break;
486
- case "table":
487
- if (Utils.isObject(value)) {
488
- if (
489
- value.hasOwnProperty("id") &&
490
- (Utils.isValidID(value.id) || Utils.isNumber(value))
491
- )
492
- return Utils.isNumber(value.id)
493
- ? Number(value.id)
494
- : UtilsServer.decodeID(value.id, this.salt);
495
- } else if (Utils.isValidID(value) || Utils.isNumber(value))
496
- return Utils.isNumber(value)
497
- ? Number(value)
498
- : UtilsServer.decodeID(value, this.salt);
499
- break;
500
- case "password":
501
- return value.length === 161 ? value : UtilsServer.hashPassword(value);
502
- case "number":
503
- return Utils.isNumber(value) ? Number(value) : null;
504
- case "id":
505
- return Utils.isNumber(value)
506
- ? value
507
- : UtilsServer.decodeID(value, this.salt);
508
- default:
509
- return value;
510
- }
511
- return null;
512
- };
513
-
514
- this.validateData(data, schema, formatOnlyAvailiableKeys);
515
-
516
- if (Utils.isArrayOfObjects(data))
517
- return data.map((single_data: Data) =>
518
- this.formatData(single_data, schema, formatOnlyAvailiableKeys)
519
- );
520
- else if (Utils.isObject(data)) {
521
- let RETURN: Data = {};
522
- for (const field of schema) {
523
- if (!data.hasOwnProperty(field.key)) {
524
- if (formatOnlyAvailiableKeys || !field.required) continue;
525
- RETURN[field.key] = this.getDefaultValue(field);
526
- continue;
527
- }
528
- RETURN[field.key] = formatField(data[field.key], field);
529
- }
530
- return RETURN;
531
- } else return [];
532
- }
533
-
534
- private getDefaultValue(field: Field): any {
535
- if (Array.isArray(field.type))
536
- return this.getDefaultValue({
537
- ...field,
538
- type: field.type.sort(
539
- (a: FieldType, b: FieldType) =>
540
- Number(b === "array") - Number(a === "array") ||
541
- Number(a === "string") - Number(b === "string") ||
542
- Number(a === "number") - Number(b === "number")
543
- )[0],
544
- } as Field);
545
-
546
- switch (field.type) {
547
- case "array":
548
- return Utils.isArrayOfObjects(field.children)
549
- ? [
550
- this.getDefaultValue({
551
- ...field,
552
- type: "object",
553
- children: field.children as Schema,
554
- }),
555
- ]
556
- : [];
557
- case "object":
558
- return Utils.combineObjects(
559
- field.children.map((f) => ({ [f.key]: this.getDefaultValue(f) }))
560
- );
561
- case "boolean":
562
- return false;
563
- default:
564
- return null;
565
- }
566
- }
567
-
568
- public joinPathesContents(
569
- mainPath: string,
570
- data: Data | Data[]
571
- ): { [key: string]: string[] } {
572
- const CombineData = (_data: Data | Data[], prefix?: string) => {
573
- let RETURN: Record<
574
- string,
575
- string | boolean | number | null | (string | boolean | number | null)[]
576
- > = {};
577
- const combineObjectsToArray = (input: any[]) =>
578
- input.reduce(
579
- (r, c) => (
580
- Object.keys(c).map((k) => (r[k] = [...(r[k] || []), c[k]])), r
581
- ),
582
- {}
583
- );
584
- if (Utils.isArrayOfObjects(_data))
585
- RETURN = combineObjectsToArray(
586
- (_data as Data[]).map((single_data) => CombineData(single_data))
587
- );
588
- else {
589
- for (const [key, value] of Object.entries(_data as Data)) {
590
- if (Utils.isObject(value))
591
- Object.assign(RETURN, CombineData(value, `${key}.`));
592
- else if (Array.isArray(value)) {
593
- if (Utils.isArrayOfObjects(value)) {
594
- Object.assign(
595
- RETURN,
596
- CombineData(
597
- combineObjectsToArray(value),
598
- (prefix ?? "") + key + "."
599
- )
600
- );
601
- } else if (
602
- Utils.isArrayOfArrays(value) &&
603
- value.every(Utils.isArrayOfObjects)
604
- )
605
- Object.assign(
606
- RETURN,
607
- CombineData(
608
- combineObjectsToArray(value.map(combineObjectsToArray)),
609
- (prefix ?? "") + key + "."
610
- )
611
- );
612
- else
613
- RETURN[(prefix ?? "") + key] = File.encode(value) as
614
- | boolean
615
- | number
616
- | string
617
- | null;
618
- } else
619
- RETURN[(prefix ?? "") + key] = File.encode(value) as
620
- | boolean
621
- | number
622
- | string
623
- | null;
624
- }
625
- }
626
- return RETURN;
627
- };
628
- const addPathToKeys = (obj: Record<string, any>, path: string) => {
629
- const newObject: Record<string, any> = {};
630
-
631
- for (const key in obj) newObject[join(path, key + ".inib")] = obj[key];
632
-
633
- return newObject;
634
- };
635
- return addPathToKeys(CombineData(data), mainPath);
636
- }
637
-
638
- public async get(
639
- tableName: string,
640
- where?: string | number | (string | number)[] | Criteria,
641
- options: Options = {
642
- page: 1,
643
- per_page: 15,
644
- },
645
- onlyLinesNumbers?: boolean
646
- ): Promise<Data | Data[] | number[] | null> {
647
- if (!options.columns) options.columns = [];
648
- else if (!Array.isArray(options.columns))
649
- options.columns = [options.columns];
650
- if (options.columns.length && !(options.columns as string[]).includes("id"))
651
- options.columns.push("id");
652
- if (!options.page) options.page = 1;
653
- if (!options.per_page) options.per_page = 15;
654
- let RETURN!: Data | Data[] | null;
655
- let schema = await this.getTableSchema(tableName);
656
- if (!schema) throw this.throwError("NO_SCHEMA", tableName);
657
- const idFilePath = join(this.folder, this.database, tableName, "id.inib");
658
- if (!(await File.isExists(idFilePath))) return null;
659
- const filterSchemaByColumns = (schema: Schema, columns: string[]): Schema =>
660
- schema
661
- .map((field) => {
662
- if (columns.some((column) => column.startsWith("!")))
663
- return columns.includes("!" + field.key) ? null : field;
664
- if (columns.includes(field.key) || columns.includes("*"))
665
- return field;
666
-
667
- if (
668
- (field.type === "array" || field.type === "object") &&
669
- Utils.isArrayOfObjects(field.children) &&
670
- columns.filter(
671
- (column) =>
672
- column.startsWith(field.key + ".") ||
673
- column.startsWith("!" + field.key + ".")
674
- ).length
675
- ) {
676
- field.children = filterSchemaByColumns(
677
- field.children as Schema,
678
- columns
679
- .filter(
680
- (column) =>
681
- column.startsWith(field.key + ".") ||
682
- column.startsWith("!" + field.key + ".")
683
- )
684
- .map((column) => column.replace(field.key + ".", ""))
685
- );
686
- return field;
687
- }
688
- return null;
689
- })
690
- .filter((i) => i) as Schema;
691
- if (options.columns.length)
692
- schema = filterSchemaByColumns(schema, options.columns);
693
-
694
- const getItemsFromSchema = async (
695
- path: string,
696
- schema: Schema,
697
- linesNumber: number[],
698
- prefix?: string
699
- ) => {
700
- let RETURN: Record<number, Data> = {};
701
- for (const field of schema) {
702
- if (
703
- (field.type === "array" ||
704
- (Array.isArray(field.type) &&
705
- (field.type as any).includes("array"))) &&
706
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
707
- .children
708
- ) {
709
- if (
710
- Utils.isArrayOfObjects(
711
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
712
- .children
713
- )
714
- ) {
715
- if (
716
- (
717
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
718
- .children as Schema
719
- ).filter(
720
- (children) =>
721
- children.type === "array" &&
722
- Utils.isArrayOfObjects(children.children)
723
- ).length
724
- ) {
725
- // one of children has array field type and has children array of object = Schema
726
- Object.entries(
727
- (await getItemsFromSchema(
728
- path,
729
- (
730
- (
731
- field as FieldDefault &
732
- (FieldArrayType | FieldArrayArrayType)
733
- ).children as Schema
734
- ).filter(
735
- (children) =>
736
- children.type === "array" &&
737
- Utils.isArrayOfObjects(children.children)
738
- ),
739
- linesNumber,
740
- (prefix ?? "") + field.key + "."
741
- )) ?? {}
742
- ).forEach(([index, item]) => {
743
- if (Utils.isObject(item)) {
744
- if (!RETURN[index]) RETURN[index] = {};
745
- if (!RETURN[index][field.key]) RETURN[index][field.key] = [];
746
- for (const child_field of (
747
- (
748
- field as FieldDefault &
749
- (FieldArrayType | FieldArrayArrayType)
750
- ).children as Schema
751
- ).filter(
752
- (children) =>
753
- children.type === "array" &&
754
- Utils.isArrayOfObjects(children.children)
755
- )) {
756
- if (Utils.isObject(item[child_field.key])) {
757
- Object.entries(item[child_field.key]).forEach(
758
- ([key, value]) => {
759
- for (let _i = 0; _i < value.length; _i++) {
760
- if (!RETURN[index][field.key][_i])
761
- RETURN[index][field.key][_i] = {};
762
- if (!RETURN[index][field.key][_i][child_field.key])
763
- RETURN[index][field.key][_i][child_field.key] =
764
- [];
765
- value[_i].forEach((_element, _index) => {
766
- if (
767
- !RETURN[index][field.key][_i][child_field.key][
768
- _index
769
- ]
770
- )
771
- RETURN[index][field.key][_i][child_field.key][
772
- _index
773
- ] = {};
774
- RETURN[index][field.key][_i][child_field.key][
775
- _index
776
- ][key] = _element;
777
- });
778
- }
779
- }
780
- );
781
- }
782
- }
783
- }
784
- });
785
- (
786
- field as FieldDefault & (FieldArrayType | FieldArrayArrayType)
787
- ).children = (
788
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
789
- .children as Schema
790
- ).filter(
791
- (children) =>
792
- children.type !== "array" ||
793
- !Utils.isArrayOfObjects(children.children)
794
- );
795
- }
796
- Object.entries(
797
- (await getItemsFromSchema(
798
- path,
799
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
800
- .children as Schema,
801
- linesNumber,
802
- (prefix ?? "") + field.key + "."
803
- )) ?? {}
804
- ).forEach(([index, item]) => {
805
- if (!RETURN[index]) RETURN[index] = {};
806
- if (Utils.isObject(item)) {
807
- if (!Object.values(item).every((i) => i === null)) {
808
- if (RETURN[index][field.key])
809
- Object.entries(item).forEach(([key, value], _index) => {
810
- RETURN[index][field.key] = RETURN[index][field.key].map(
811
- (_obj, _i) => ({ ..._obj, [key]: value[_i] })
812
- );
813
- });
814
- else if (Object.values(item).every(Utils.isArrayOfArrays))
815
- RETURN[index][field.key] = item;
816
- else {
817
- RETURN[index][field.key] = [];
818
- Object.entries(item).forEach(([key, value]) => {
819
- for (let _i = 0; _i < value.length; _i++) {
820
- if (!RETURN[index][field.key][_i])
821
- RETURN[index][field.key][_i] = {};
822
- RETURN[index][field.key][_i][key] = value[_i];
823
- }
824
- });
825
- }
826
- } else RETURN[index][field.key] = null;
827
- } else RETURN[index][field.key] = item;
828
- });
829
- } else if (
830
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
831
- .children === "table" ||
832
- (Array.isArray(
833
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
834
- .children
835
- ) &&
836
- (
837
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
838
- .children as FieldType[]
839
- ).includes("table"))
840
- ) {
841
- if (options.columns)
842
- options.columns = (options.columns as string[])
843
- .filter((column) => column.includes(`${field.key}.`))
844
- .map((column) => column.replace(`${field.key}.`, ""));
845
- const [items, total_lines] = await File.get(
846
- join(path, (prefix ?? "") + field.key + ".inib"),
847
- linesNumber,
848
- field.type,
849
- (field as FieldDefault & (FieldArrayType | FieldArrayArrayType))
850
- .children as FieldType | FieldType[],
851
- this.salt
852
- );
853
-
854
- this.totalItems[tableName + "-" + field.key] = total_lines;
855
- for (const [index, item] of Object.entries(items)) {
856
- if (!RETURN[index]) RETURN[index] = {};
857
- RETURN[index][field.key] = item
858
- ? await this.get(field.key, item as number, options)
859
- : this.getDefaultValue(field);
860
- }
861
- } else if (
862
- await File.isExists(
863
- join(path, (prefix ?? "") + field.key + ".inib")
864
- )
865
- ) {
866
- const [items, total_lines] = await File.get(
867
- join(path, (prefix ?? "") + field.key + ".inib"),
868
- linesNumber,
869
- field.type,
870
- (field as any)?.children,
871
- this.salt
872
- );
873
-
874
- this.totalItems[tableName + "-" + field.key] = total_lines;
875
- for (const [index, item] of Object.entries(items)) {
876
- if (!RETURN[index]) RETURN[index] = {};
877
- RETURN[index][field.key] = item ?? this.getDefaultValue(field);
878
- }
879
- }
880
- } else if (field.type === "object") {
881
- for (const [index, item] of Object.entries(
882
- (await getItemsFromSchema(
883
- path,
884
- field.children as Schema,
885
- linesNumber,
886
- (prefix ?? "") + field.key + "."
887
- )) ?? {}
888
- )) {
889
- if (!RETURN[index]) RETURN[index] = {};
890
- if (Utils.isObject(item)) {
891
- if (!Object.values(item).every((i) => i === null))
892
- RETURN[index][field.key] = item;
893
- else RETURN[index][field.key] = null;
894
- } else RETURN[index][field.key] = null;
895
- }
896
- } else if (field.type === "table") {
897
- if (
898
- (await File.isExists(
899
- join(this.folder, this.database, field.key)
900
- )) &&
901
- (await File.isExists(
902
- join(path, (prefix ?? "") + field.key + ".inib")
903
- ))
904
- ) {
905
- if (options.columns)
906
- options.columns = (options.columns as string[])
907
- .filter(
908
- (column) =>
909
- column.includes(`${field.key}.`) &&
910
- !column.includes(`${field.key}.`)
911
- )
912
- .map((column) => column.replace(`${field.key}.`, ""));
913
- const [items, total_lines] = await File.get(
914
- join(path, (prefix ?? "") + field.key + ".inib"),
915
- linesNumber,
916
- "number",
917
- undefined,
918
- this.salt
919
- );
920
- this.totalItems[tableName + "-" + field.key] = total_lines;
921
- for (const [index, item] of Object.entries(items)) {
922
- if (!RETURN[index]) RETURN[index] = {};
923
- RETURN[index][field.key] = item
924
- ? await this.get(field.key, item as number, options)
925
- : this.getDefaultValue(field);
926
- }
927
- }
928
- } else if (
929
- await File.isExists(join(path, (prefix ?? "") + field.key + ".inib"))
930
- ) {
931
- const [items, total_lines] = await File.get(
932
- join(path, (prefix ?? "") + field.key + ".inib"),
933
- linesNumber,
934
- field.type,
935
- (field as any)?.children,
936
- this.salt
937
- );
938
-
939
- this.totalItems[tableName + "-" + field.key] = total_lines;
940
- for (const [index, item] of Object.entries(items)) {
941
- if (!RETURN[index]) RETURN[index] = {};
942
- RETURN[index][field.key] = item ?? this.getDefaultValue(field);
943
- }
944
- }
945
- }
946
- return RETURN;
947
- };
948
- if (!where) {
949
- // Display all data
950
- RETURN = Object.values(
951
- await getItemsFromSchema(
952
- join(this.folder, this.database, tableName),
953
- schema,
954
- Array.from(
955
- { length: options.per_page },
956
- (_, index) =>
957
- ((options.page as number) - 1) * (options.per_page as number) +
958
- index +
959
- 1
960
- )
961
- )
962
- );
963
- } else if (Utils.isValidID(where) || Utils.isNumber(where)) {
964
- let Ids = where as string | number | (string | number)[];
965
- if (!Array.isArray(Ids)) Ids = [Ids];
966
- const [lineNumbers, countItems] = await File.search(
967
- idFilePath,
968
- "[]",
969
- Utils.isNumber(Ids)
970
- ? Ids.map((id) => Number(id as string))
971
- : Ids.map((id) => UtilsServer.decodeID(id as string, this.salt)),
972
- undefined,
973
- "number",
974
- undefined,
975
- Ids.length,
976
- 0,
977
- false,
978
- this.salt
979
- );
980
- if (!lineNumbers || !Object.keys(lineNumbers).length)
981
- throw this.throwError(
982
- "INVALID_ID",
983
- where as number | string | (number | string)[]
984
- );
985
- RETURN = Object.values(
986
- (await getItemsFromSchema(
987
- join(this.folder, this.database, tableName),
988
- schema,
989
- Object.keys(lineNumbers).map(Number)
990
- )) ?? {}
991
- );
992
- if (RETURN.length && !Array.isArray(where)) RETURN = RETURN[0];
993
- } else if (Utils.isObject(where)) {
994
- // Criteria
995
- const FormatObjectCriteriaValue = (
996
- value: string,
997
- isParentArray: boolean = false
998
- ): [ComparisonOperator, string | number | boolean | null] => {
999
- switch (value[0]) {
1000
- case ">":
1001
- case "<":
1002
- case "[":
1003
- return ["=", "]", "*"].includes(value[1])
1004
- ? [
1005
- value.slice(0, 2) as ComparisonOperator,
1006
- value.slice(2) as string | number,
1007
- ]
1008
- : [
1009
- value.slice(0, 1) as ComparisonOperator,
1010
- value.slice(1) as string | number,
1011
- ];
1012
- case "!":
1013
- return ["=", "*"].includes(value[1])
1014
- ? [
1015
- value.slice(0, 2) as ComparisonOperator,
1016
- value.slice(2) as string | number,
1017
- ]
1018
- : value[1] === "["
1019
- ? [
1020
- value.slice(0, 3) as ComparisonOperator,
1021
- value.slice(3) as string | number,
1022
- ]
1023
- : [
1024
- (value.slice(0, 1) + "=") as ComparisonOperator,
1025
- value.slice(1) as string | number,
1026
- ];
1027
- case "=":
1028
- return isParentArray
1029
- ? [
1030
- value.slice(0, 1) as ComparisonOperator,
1031
- value.slice(1) as string | number,
1032
- ]
1033
- : [
1034
- value.slice(0, 1) as ComparisonOperator,
1035
- (value.slice(1) + ",") as string,
1036
- ];
1037
- case "*":
1038
- return [
1039
- value.slice(0, 1) as ComparisonOperator,
1040
- value.slice(1) as string | number,
1041
- ];
1042
- default:
1043
- return ["=", value];
1044
- }
1045
- };
1046
-
1047
- const applyCriteria = async (
1048
- criteria?: Criteria,
1049
- allTrue?: boolean
1050
- ): Promise<Record<number, Data> | null> => {
1051
- let RETURN: Record<number, Data> = {};
1052
- if (!criteria) return null;
1053
- if (criteria.and && Utils.isObject(criteria.and)) {
1054
- const searchResult = await applyCriteria(
1055
- criteria.and as Criteria,
1056
- true
1057
- );
1058
- if (searchResult) {
1059
- RETURN = Utils.deepMerge(
1060
- RETURN,
1061
- Object.fromEntries(
1062
- Object.entries(searchResult).filter(
1063
- ([_k, v], _i) =>
1064
- Object.keys(v).length ===
1065
- Object.keys(criteria.and ?? {}).length
1066
- )
1067
- )
1068
- );
1069
- delete criteria.and;
1070
- } else return null;
1071
- }
1072
-
1073
- if (criteria.or && Utils.isObject(criteria.or)) {
1074
- const searchResult = await applyCriteria(criteria.or as Criteria);
1075
- delete criteria.or;
1076
- if (searchResult) RETURN = Utils.deepMerge(RETURN, searchResult);
1077
- }
1078
-
1079
- if (Object.keys(criteria).length > 0) {
1080
- allTrue = true;
1081
- let index = -1;
1082
- for (const [key, value] of Object.entries(criteria)) {
1083
- const field = this.getField(key, schema as Schema) as Field;
1084
- index++;
1085
- let searchOperator:
1086
- | ComparisonOperator
1087
- | ComparisonOperator[]
1088
- | undefined = undefined,
1089
- searchComparedAtValue:
1090
- | string
1091
- | number
1092
- | boolean
1093
- | null
1094
- | (string | number | boolean | null)[]
1095
- | undefined = undefined,
1096
- searchLogicalOperator: "and" | "or" | undefined = undefined;
1097
- if (Utils.isObject(value)) {
1098
- if (
1099
- (value as Criteria)?.or &&
1100
- Array.isArray((value as Criteria).or)
1101
- ) {
1102
- const searchCriteria = (
1103
- (value as Criteria).or as (string | number | boolean)[]
1104
- )
1105
- .map(
1106
- (
1107
- single_or
1108
- ): [ComparisonOperator, string | number | boolean | null] =>
1109
- typeof single_or === "string"
1110
- ? FormatObjectCriteriaValue(single_or)
1111
- : ["=", single_or]
1112
- )
1113
- .filter((a) => a) as [ComparisonOperator, string | number][];
1114
- if (searchCriteria.length > 0) {
1115
- searchOperator = searchCriteria.map(
1116
- (single_or) => single_or[0]
1117
- );
1118
- searchComparedAtValue = searchCriteria.map(
1119
- (single_or) => single_or[1]
1120
- );
1121
- searchLogicalOperator = "or";
1122
- }
1123
- delete (value as Criteria).or;
1124
- }
1125
- if (
1126
- (value as Criteria)?.and &&
1127
- Array.isArray((value as Criteria).and)
1128
- ) {
1129
- const searchCriteria = (
1130
- (value as Criteria).and as (string | number | boolean)[]
1131
- )
1132
- .map(
1133
- (
1134
- single_and
1135
- ): [ComparisonOperator, string | number | boolean | null] =>
1136
- typeof single_and === "string"
1137
- ? FormatObjectCriteriaValue(single_and)
1138
- : ["=", single_and]
1139
- )
1140
- .filter((a) => a) as [ComparisonOperator, string | number][];
1141
- if (searchCriteria.length > 0) {
1142
- searchOperator = searchCriteria.map(
1143
- (single_and) => single_and[0]
1144
- );
1145
- searchComparedAtValue = searchCriteria.map(
1146
- (single_and) => single_and[1]
1147
- );
1148
- searchLogicalOperator = "and";
1149
- }
1150
- delete (value as Criteria).and;
1151
- }
1152
- } else if (Array.isArray(value)) {
1153
- const searchCriteria = value
1154
- .map(
1155
- (
1156
- single
1157
- ): [ComparisonOperator, string | number | boolean | null] =>
1158
- typeof single === "string"
1159
- ? FormatObjectCriteriaValue(single)
1160
- : ["=", single]
1161
- )
1162
- .filter((a) => a) as [ComparisonOperator, string | number][];
1163
- if (searchCriteria.length > 0) {
1164
- searchOperator = searchCriteria.map((single) => single[0]);
1165
- searchComparedAtValue = searchCriteria.map(
1166
- (single) => single[1]
1167
- );
1168
- searchLogicalOperator = "and";
1169
- }
1170
- } else if (typeof value === "string") {
1171
- const ComparisonOperatorValue = FormatObjectCriteriaValue(value);
1172
- if (ComparisonOperatorValue) {
1173
- searchOperator = ComparisonOperatorValue[0];
1174
- searchComparedAtValue = ComparisonOperatorValue[1];
1175
- }
1176
- } else {
1177
- searchOperator = "=";
1178
- searchComparedAtValue = value as number | boolean;
1179
- }
1180
- const [searchResult, total_lines] = await File.search(
1181
- join(this.folder, this.database, tableName, key + ".inib"),
1182
- searchOperator,
1183
- searchComparedAtValue,
1184
- searchLogicalOperator,
1185
- field?.type,
1186
- (field as any)?.children,
1187
- options.per_page,
1188
- (options.page as number) - 1 * (options.per_page as number) + 1,
1189
- true,
1190
- this.salt
1191
- );
1192
- if (searchResult) {
1193
- RETURN = Utils.deepMerge(RETURN, searchResult);
1194
- this.totalItems[tableName + "-" + key] = total_lines;
1195
- }
1196
- if (allTrue && index > 0) {
1197
- if (!Object.keys(RETURN).length) RETURN = {};
1198
- RETURN = Object.fromEntries(
1199
- Object.entries(RETURN).filter(
1200
- ([_index, item]) => Object.keys(item).length > index
1201
- )
1202
- );
1203
- if (!Object.keys(RETURN).length) RETURN = {};
1204
- }
1205
- }
1206
- }
1207
- return Object.keys(RETURN).length ? RETURN : null;
1208
- };
1209
-
1210
- RETURN = await applyCriteria(where as Criteria);
1211
- if (RETURN) {
1212
- if (onlyLinesNumbers) return Object.keys(RETURN).map(Number);
1213
- const alreadyExistsColumns = Object.keys(Object.values(RETURN)[0]).map(
1214
- (key) => parse(key).name
1215
- );
1216
- RETURN = Object.values(
1217
- Utils.deepMerge(
1218
- await getItemsFromSchema(
1219
- join(this.folder, this.database, tableName),
1220
- schema.filter(
1221
- (field) => !alreadyExistsColumns.includes(field.key)
1222
- ),
1223
- Object.keys(RETURN).map(Number)
1224
- ),
1225
- RETURN
1226
- )
1227
- );
1228
- }
1229
- }
1230
- if (
1231
- !RETURN ||
1232
- (Utils.isObject(RETURN) && !Object.keys(RETURN).length) ||
1233
- (Array.isArray(RETURN) && !RETURN.length)
1234
- )
1235
- return null;
1236
-
1237
- const greatestTotalItems = Math.max(
1238
- ...Object.entries(this.totalItems)
1239
- .filter(([k]) => k.startsWith(tableName + "-"))
1240
- .map(([, v]) => v)
1241
- );
1242
- this.pageInfo = {
1243
- ...(({ columns, ...restOfOptions }) => restOfOptions)(options),
1244
- total_pages: Math.ceil(greatestTotalItems / options.per_page),
1245
- total: greatestTotalItems,
1246
- };
1247
- return RETURN;
1248
- }
1249
-
1250
- public async post(
1251
- tableName: string,
1252
- data: Data | Data[],
1253
- options: Options = {
1254
- page: 1,
1255
- per_page: 15,
1256
- },
1257
- returnPostedData: boolean = true
1258
- ): Promise<Data | Data[] | null | void> {
1259
- const schema = await this.getTableSchema(tableName);
1260
- let RETURN: Data | Data[] | null | undefined;
1261
- if (!schema) throw this.throwError("NO_SCHEMA", tableName);
1262
- const idFilePath = join(this.folder, this.database, tableName, "id.inib");
1263
- let last_id = (await File.isExists(idFilePath))
1264
- ? Number(
1265
- Object.values(
1266
- await File.get(idFilePath, -1, "number", undefined, this.salt)
1267
- )[0]
1268
- )
1269
- : 0;
1270
- if (Utils.isArrayOfObjects(data))
1271
- (data as Data[]).forEach((single_data, index) => {
1272
- if (!RETURN) RETURN = [];
1273
- RETURN[index] = (({ id, updated_at, created_at, ...rest }) => ({
1274
- id: ++last_id,
1275
- ...rest,
1276
- created_at: new Date(),
1277
- }))(single_data);
1278
- });
1279
- else
1280
- RETURN = (({ id, updated_at, created_at, ...rest }) => ({
1281
- id: ++last_id,
1282
- ...rest,
1283
- created_at: new Date(),
1284
- }))(data as Data);
1285
- if (!RETURN) throw this.throwError("NO_DATA");
1286
- RETURN = this.formatData(RETURN, schema);
1287
- const pathesContents = this.joinPathesContents(
1288
- join(this.folder, this.database, tableName),
1289
- RETURN
1290
- );
1291
- for await (const [path, content] of Object.entries(pathesContents))
1292
- await appendFile(
1293
- path,
1294
- (Array.isArray(content) ? content.join("\n") : content ?? "") + "\n"
1295
- );
1296
-
1297
- if (returnPostedData)
1298
- return this.get(
1299
- tableName,
1300
- Utils.isArrayOfObjects(RETURN)
1301
- ? RETURN.map((data: Data) => data.id)
1302
- : ((RETURN as Data).id as number),
1303
- options
1304
- );
1305
- }
1306
-
1307
- public async put(
1308
- tableName: string,
1309
- data: Data | Data[],
1310
- where?: number | string | (number | string)[] | Criteria,
1311
- options: Options = {
1312
- page: 1,
1313
- per_page: 15,
1314
- },
1315
- returnPostedData: boolean = true
1316
- ): Promise<Data | Data[] | null | void> {
1317
- const schema = await this.getTableSchema(tableName);
1318
- if (!schema) throw this.throwError("NO_SCHEMA", tableName);
1319
- const idFilePath = join(this.folder, this.database, tableName, "id.inib");
1320
- if (!(await File.isExists(idFilePath)))
1321
- throw this.throwError("NO_ITEMS", tableName);
1322
- data = this.formatData(data, schema, true);
1323
- if (!where) {
1324
- if (Utils.isArrayOfObjects(data)) {
1325
- if (
1326
- !(data as Data[]).every(
1327
- (item) => item.hasOwnProperty("id") && Utils.isValidID(item.id)
1328
- )
1329
- )
1330
- throw this.throwError("INVALID_ID");
1331
- return this.put(
1332
- tableName,
1333
- data,
1334
- (data as Data[]).map((item) => item.id)
1335
- );
1336
- } else if (data.hasOwnProperty("id")) {
1337
- if (!Utils.isValidID((data as Data).id))
1338
- throw this.throwError("INVALID_ID", (data as Data).id);
1339
- return this.put(
1340
- tableName,
1341
- data,
1342
- UtilsServer.decodeID((data as Data).id as string, this.salt)
1343
- );
1344
- } else {
1345
- const pathesContents = this.joinPathesContents(
1346
- join(this.folder, this.database, tableName),
1347
- Utils.isArrayOfObjects(data)
1348
- ? (data as Data[]).map((item) => ({
1349
- ...(({ id, ...restOfData }) => restOfData)(item),
1350
- updated_at: new Date(),
1351
- }))
1352
- : {
1353
- ...(({ id, ...restOfData }) => restOfData)(data as Data),
1354
- updated_at: new Date(),
1355
- }
1356
- );
1357
- for (const [path, content] of Object.entries(pathesContents))
1358
- await File.replace(path, content);
1359
- if (returnPostedData) return this.get(tableName, where, options);
1360
- }
1361
- } else if (Utils.isValidID(where)) {
1362
- let Ids = where as string | string[];
1363
- if (!Array.isArray(Ids)) Ids = [Ids];
1364
- const [lineNumbers, countItems] = await File.search(
1365
- idFilePath,
1366
- "[]",
1367
- Ids.map((id) => UtilsServer.decodeID(id, this.salt)),
1368
- undefined,
1369
- "number",
1370
- undefined,
1371
- Ids.length,
1372
- 0,
1373
- false,
1374
- this.salt
1375
- );
1376
- if (!lineNumbers || !Object.keys(lineNumbers).length)
1377
- throw this.throwError("INVALID_ID");
1378
- return this.put(tableName, data, Object.keys(lineNumbers).map(Number));
1379
- } else if (Utils.isNumber(where)) {
1380
- // "where" in this case, is the line(s) number(s) and not id(s)
1381
- const pathesContents = Object.fromEntries(
1382
- Object.entries(
1383
- this.joinPathesContents(
1384
- join(this.folder, this.database, tableName),
1385
- Utils.isArrayOfObjects(data)
1386
- ? (data as Data[]).map((item) => ({
1387
- ...item,
1388
- updated_at: new Date(),
1389
- }))
1390
- : { ...data, updated_at: new Date() }
1391
- )
1392
- ).map(([key, value]) => [
1393
- key,
1394
- ([...(Array.isArray(where) ? where : [where])] as number[]).reduce(
1395
- (obj, key, index) => ({
1396
- ...obj,
1397
- [key]: Array.isArray(value) ? value[index] : value,
1398
- }),
1399
- {}
1400
- ),
1401
- ])
1402
- );
1403
- for (const [path, content] of Object.entries(pathesContents))
1404
- await File.replace(path, content);
1405
- if (returnPostedData) return this.get(tableName, where, options);
1406
- } else if (typeof where === "object" && !Array.isArray(where)) {
1407
- const lineNumbers = this.get(tableName, where, undefined, true);
1408
- if (!lineNumbers || !Array.isArray(lineNumbers) || !lineNumbers.length)
1409
- throw this.throwError("NO_ITEMS", tableName);
1410
- return this.put(tableName, data, lineNumbers);
1411
- } else throw this.throwError("INVALID_PARAMETERS", tableName);
1412
- }
1413
-
1414
- public async delete(
1415
- tableName: string,
1416
- where?: number | string | (number | string)[] | Criteria,
1417
- _id?: string | string[]
1418
- ): Promise<string | string[] | null> {
1419
- const schema = await this.getTableSchema(tableName);
1420
- if (!schema) throw this.throwError("NO_SCHEMA", tableName);
1421
- const idFilePath = join(this.folder, this.database, tableName, "id.inib");
1422
- if (!(await File.isExists(idFilePath)))
1423
- throw this.throwError("NO_ITEMS", tableName);
1424
- if (!where) {
1425
- const files = await readdir(join(this.folder, this.database, tableName));
1426
- if (files.length) {
1427
- for (const file in files.filter(
1428
- (fileName: string) => fileName !== "schema"
1429
- ))
1430
- await unlink(join(this.folder, this.database, tableName, file));
1431
- }
1432
- return "*";
1433
- } else if (Utils.isValidID(where)) {
1434
- let Ids = where as string | string[];
1435
- if (!Array.isArray(Ids)) Ids = [Ids];
1436
- const [lineNumbers, countItems] = await File.search(
1437
- idFilePath,
1438
- "[]",
1439
- Ids.map((id) => UtilsServer.decodeID(id, this.salt)),
1440
- undefined,
1441
- "number",
1442
- undefined,
1443
- Ids.length,
1444
- 0,
1445
- false,
1446
- this.salt
1447
- );
1448
- if (!lineNumbers || !Object.keys(lineNumbers).length)
1449
- throw this.throwError("INVALID_ID");
1450
- return this.delete(
1451
- tableName,
1452
- Object.keys(lineNumbers).map(Number),
1453
- where as string | string[]
1454
- );
1455
- } else if (Utils.isNumber(where)) {
1456
- const files = await readdir(join(this.folder, this.database, tableName));
1457
- if (files.length) {
1458
- if (!_id)
1459
- _id = Object.values(
1460
- await File.get(
1461
- join(this.folder, this.database, tableName, "id.inib"),
1462
- where as number | number[],
1463
- "number",
1464
- undefined,
1465
- this.salt
1466
- )
1467
- )
1468
- .map(Number)
1469
- .map((id) => UtilsServer.encodeID(id, this.salt));
1470
- for (const file of files.filter(
1471
- (fileName: string) =>
1472
- fileName.endsWith(".inib") && fileName !== "schema"
1473
- ))
1474
- await File.remove(
1475
- join(this.folder, this.database, tableName, file),
1476
- where as number | number[]
1477
- );
1478
- return Array.isArray(_id) && _id.length === 1 ? _id[0] : _id;
1479
- }
1480
- } else if (typeof where === "object" && !Array.isArray(where)) {
1481
- const lineNumbers = this.get(tableName, where, undefined, true);
1482
- if (!lineNumbers || !Array.isArray(lineNumbers) || !lineNumbers.length)
1483
- throw this.throwError("NO_ITEMS", tableName);
1484
- return this.delete(tableName, lineNumbers);
1485
- } else throw this.throwError("INVALID_PARAMETERS", tableName);
1486
- return null;
1487
- }
1488
- }