inibase 1.0.0-rc.3 → 1.0.0-rc.30

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