inibase 1.0.0-rc.8 → 1.0.0-rc.81

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