inibase 1.0.0-rc.0

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