This commit is contained in:
Peter Maquiran
2023-02-27 09:31:10 +01:00
parent 6e2669e52f
commit 4731b402df
87 changed files with 86 additions and 4253 deletions
-5
View File
@@ -1,5 +0,0 @@
import { DatabaseSchema, TableSchema } from '../models/register-modal.interface.js';
import { actionParam, dbType } from './intreface.js';
export declare class DBSwitch {
static requestHandler(TableSchema: TableSchema, DBconfig: DatabaseSchema, dbType: dbType, action: actionParam, arg: any, queryId: any): Promise<any>;
}
-29
View File
@@ -1,29 +0,0 @@
import { indexedDB } from './indexedDb/indexedb.js';
import { IndexedDBWorkerQueue } from './worker.queue.js';
export class DBSwitch {
static async requestHandler(TableSchema, DBconfig, dbType, action, arg, queryId) {
if (typeof (Worker) !== "undefined" && IndexedDBWorkerQueue.webWorkerModuleSupport) {
//great, your browser supports web workers
return new Promise(async (resolve, reject) => {
const request = IndexedDBWorkerQueue.register({
params: { TableSchema, DBconfig, queryId, action, arg, dbType },
method: 'execute',
func: (message) => {
if (message.queryId == queryId) {
resolve(message === null || message === void 0 ? void 0 : message.value);
return true;
}
},
});
if (request == false) {
const result = await indexedDB.requestHandler(TableSchema, DBconfig, queryId)[action](arg);
resolve(result === null || result === void 0 ? void 0 : result.value);
}
});
}
else {
const result = await indexedDB.requestHandler(TableSchema, DBconfig, queryId)[action](arg);
return result === null || result === void 0 ? void 0 : result.value;
}
}
}
-7
View File
@@ -1,7 +0,0 @@
import { DatabaseSchema } from '../../models/register-modal.interface.js';
export declare class IndexedDBConnection {
constructor();
static connect(config: DatabaseSchema): Promise<IDBDatabase>;
static migrate(config: DatabaseSchema): Promise<boolean>;
private runMigrations;
}
@@ -1,62 +0,0 @@
// inspire by https://github.com/hc-oss/use-indexeddb
export class IndexedDBConnection {
constructor() { }
connect(config) {
return new Promise((resolve, reject) => {
const idbInstance = indexedDB || self.indexedDB || self.mozIndexedDB || self.webkitIndexedDB || self.msIndexedDB;
if (idbInstance) {
const request = idbInstance.open(config.databaseName, config.version);
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = (e) => {
reject(e.target.error.name);
};
request.onupgradeneeded = async (e) => {
console.log('need to migrate first');
await this.migrate(config);
return await this.connect(config);
};
// request.onblocked = async (e: any) => {
// reject(e.target.error.name);
// }
}
else {
reject("IDBDatabase not supported inside webworker");
}
});
}
migrate(config) {
return new Promise((resolve, reject) => {
const idbInstance = indexedDB || self.indexedDB || self.mozIndexedDB || self.webkitIndexedDB || self.msIndexedDB;
if (idbInstance) {
const request = idbInstance.open(config.databaseName, config.version);
request.onsuccess = () => {
resolve(false);
};
request.onerror = (e) => {
reject(e.target.error.name);
};
request.onupgradeneeded = async (e) => {
const db = e.target.result;
await this.runMigrations(db, config);
db.close();
resolve(true);
};
}
else {
reject("Failed to connect");
}
});
}
async runMigrations(db, config) {
await config.stores.forEach(async (storeSchema) => {
if (!db.objectStoreNames.contains(storeSchema.name)) {
const ObjectStore = db.createObjectStore(storeSchema.name, storeSchema.id);
storeSchema.fields.forEach(c => {
ObjectStore.createIndex(c.name, c.keyPath, c.options);
});
}
});
}
}
@@ -1,3 +0,0 @@
export declare class IndexedDBConnectionDynamicChange {
changeSchema(db: any, schemaChanges: any): void;
}
@@ -1,31 +0,0 @@
import { IndexedDBConnection } from './connector';
export class IndexedDBConnectionDynamicChange {
changeSchema(db, schemaChanges) {
db.close();
const newDb = new IndexedDBConnection().connect({
databaseName: 'databaseName',
type: 'indexedDB',
version: 0
});
// newDb.on('blocked', () => false); // Silence console warning of blocked event.
// Workaround: If DB is empty from tables, it needs to be recreated
// if (db.tables.length === 0) {
// await db.delete();
// newDb.version(1).stores(schemaChanges);
// return await newDb.open();
//}
// Extract current schema in dexie format:
const currentSchema = db.tables.reduce((result, { name, schema }) => {
result[name] = [schema.primKey.src, ...schema.indexes.map((idx) => idx.src)].join(',');
return result;
}, {});
// console.log('Version: ' + db.verno);
// console.log('Current Schema: ', currentSchema);
// Tell Dexie about current schema:
// newDb.version(db.verno).stores(currentSchema);
// Tell Dexie about next schema:
// newDb.version(db.verno + 1).stores(schemaChanges);
// Upgrade it:
// return await newDb.open();
}
}
-39
View File
@@ -1,39 +0,0 @@
import { DatabaseSchema, TableSchema } from "../../models/register-modal.interface.js";
import { Method } from "../../models/model.interface.js";
declare class _indexedDB {
private validateStore;
private validateBeforeTransaction;
private createTransaction;
migrate(config: DatabaseSchema): Promise<boolean>;
getConnection(config: DatabaseSchema): Promise<IDBDatabase>;
getActions: (currentStore: any, config: any) => {
getByID: (id: string | number) => Promise<any>;
getOneByIndex: (keyPath: string, value: string | number) => Promise<any>;
getManyByIndex: (keyPath: string, value: string | number) => Promise<any[]>;
getAll: () => Promise<any[]>;
add: (value: Object, key?: any) => Promise<number | Object>;
update: (value: any, key?: any) => Promise<any>;
deleteByID: (id: any) => Promise<any>;
deleteAll: () => Promise<any>;
openCursor: (cursorCallback: any, keyRange?: IDBKeyRange) => Promise<void | IDBCursorWithValue>;
};
requestHandler: (TableSchema: TableSchema, config: DatabaseSchema, queryId: any) => {
select: (methods: Method[]) => Promise<unknown>;
update: (methods: Method[]) => Promise<{
queryId: any;
}>;
delete: (methods: Method[]) => Promise<{
queryId: any;
value?: undefined;
} | {
queryId: any;
value: any;
}>;
insert: (methods: Method[]) => Promise<{
queryId: any;
value: any;
}>;
};
}
export declare const indexedDB: _indexedDB;
export {};
@@ -1,362 +0,0 @@
import { IndexedDBConnection } from "./connector.js";
import { SqlObject } from "../../sql/sqlObject/sqlObject.js";
// inspire by https://github.com/hc-oss/use-indexeddb
class _indexedDB {
constructor() {
this.getActions = (currentStore, config) => {
return {
getByID: (id) => {
return new Promise((resolve, reject) => {
this.getConnection(config)
.then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readonly", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
let request = objectStore.get(id);
request.onsuccess = (e) => {
resolve(e.target.result);
};
})
.catch(reject);
});
},
getOneByIndex: (keyPath, value) => {
return new Promise((resolve, reject) => {
this.getConnection(config)
.then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readonly", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
let index = objectStore.index(keyPath);
let request = index.get(value);
request.onsuccess = (e) => {
resolve(e.target.result);
};
})
.catch(reject);
});
},
getManyByIndex: (keyPath, value) => {
return new Promise((resolve, reject) => {
this.getConnection(config)
.then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readonly", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
let index = objectStore.index(keyPath);
let request = index.getAll(value);
request.onsuccess = (e) => {
resolve(e.target.result);
};
})
.catch(reject);
});
},
getAll: () => {
return new Promise((resolve, reject) => {
this.getConnection(config).then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readonly", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
let request = objectStore.getAll();
request.onsuccess = (e) => {
resolve(e.target.result);
};
})
.catch(reject);
});
},
add: (value, key) => {
return new Promise((resolve, reject) => {
this.getConnection(config).then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readwrite", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
let request = objectStore.add(value, key);
request.onsuccess = (e) => {
var _a, _b;
(_b = (_a = tx) === null || _a === void 0 ? void 0 : _a.commit) === null || _b === void 0 ? void 0 : _b.call(_a);
resolve(e.target.result);
db.transaction;
};
request.onerror = (e) => {
let data = {
error: e.target['error']
};
resolve(data);
};
})
.catch(reject);
});
},
update: (value, key) => {
return new Promise((resolve, reject) => {
this.getConnection(config).then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readwrite", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
let request = objectStore.put(value, key);
request.onsuccess = (e) => {
var _a, _b;
(_b = (_a = tx) === null || _a === void 0 ? void 0 : _a.commit) === null || _b === void 0 ? void 0 : _b.call(_a);
resolve(e.target.result);
};
})
.catch(reject);
});
},
deleteByID: (id) => {
return new Promise((resolve, reject) => {
this.getConnection(config).then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readwrite", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
let request = objectStore.delete(id);
request.onsuccess = (e) => {
var _a, _b;
(_b = (_a = tx) === null || _a === void 0 ? void 0 : _a.commit) === null || _b === void 0 ? void 0 : _b.call(_a);
resolve(e);
};
})
.catch(reject);
});
},
deleteAll: () => {
return new Promise((resolve, reject) => {
this.getConnection(config)
.then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readwrite", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
objectStore.clear();
tx.oncomplete = (e) => {
var _a, _b;
try {
(_b = (_a = tx) === null || _a === void 0 ? void 0 : _a.commit) === null || _b === void 0 ? void 0 : _b.call(_a);
resolve(e);
}
catch (error) {
resolve(e);
}
};
})
.catch(reject);
});
},
openCursor: (cursorCallback, keyRange) => {
return new Promise((resolve, reject) => {
this.getConnection(config)
.then(db => {
this.validateBeforeTransaction(db, currentStore, reject);
let tx = this.createTransaction(db, "readonly", currentStore, resolve, reject);
let objectStore = tx.objectStore(currentStore);
let request = objectStore.openCursor(keyRange);
request.onsuccess = e => {
cursorCallback(e);
resolve();
// db.close();
};
})
.catch(reject);
});
},
};
};
this.requestHandler = (TableSchema, config, queryId) => {
return {
select: async (methods) => {
if (methods[0].methodName == 'all') {
return {
queryId: queryId,
value: await this.getActions(TableSchema.name, config).getAll()
};
}
else if (methods[0].methodName == 'get') {
const args = methods[0].arguments;
if (Object.keys(args).length == 1) {
const key = Object.keys(args)[0];
const value = args[key];
if (TableSchema.id.keyPath == key) {
return {
queryId: queryId,
value: await this.getActions(TableSchema.name, config).getByID(value)
};
}
else {
return {
queryId: queryId,
value: await this.getActions(TableSchema.name, config).getOneByIndex(key, value)
};
}
}
}
else if (methods[methods.length - 1].methodName == 'execute') {
return new Promise(async (resolve, reject) => {
const sqlObject = new SqlObject(TableSchema, methods);
await this.getActions(TableSchema.name, config).openCursor(async (event) => {
var cursor = event.target.result;
if (cursor) {
const row = cursor.value;
await sqlObject.runFirstMethod(row);
cursor.continue();
}
else {
sqlObject.doneRunFirstMethod();
sqlObject.run();
resolve({
queryId: queryId,
value: sqlObject.firstMethod.rows
});
}
});
});
}
else if (methods[methods.length - 1].methodName == 'first') {
return new Promise(async (resolve, reject) => {
const sqlObject = new SqlObject(TableSchema, methods);
await this.getActions(TableSchema.name, config).openCursor(async (event) => {
var cursor = event.target.result;
if (cursor) {
const row = cursor.value;
await sqlObject.runFirstMethod(row, resolve, 1);
cursor.continue();
}
else {
sqlObject.doneRunFirstMethod();
sqlObject.run();
resolve({
queryId: queryId,
value: sqlObject.firstMethod.rows
});
}
});
});
}
},
update: async (methods) => {
if (methods[0].methodName == 'save') {
const args = methods[0].arguments;
const idFieldName = TableSchema.id.keyPath;
const idValue = args[idFieldName];
if (idValue) {
await this.getActions(TableSchema.name, config).update(args);
}
else {
await this.getActions(TableSchema.name, config).update(args, idValue);
}
return {
queryId
};
}
else if (methods[0].methodName != 'update' && methods[methods.length - 1].methodName == 'update') {
const argsToUpdate = methods[methods.length - 1].arguments;
const customMethods = Object.create(methods);
customMethods[methods.length - 1].methodName = 'execute';
const result = await this.requestHandler(TableSchema, config, queryId).select(customMethods);
const rows = result.value;
for (let row of rows) {
const updateRow = Object.assign(row, argsToUpdate);
await this.getActions(TableSchema.name, config).update(updateRow);
}
return {
queryId
};
}
else if (methods[0].methodName == 'update') {
const argsToUpdate = methods[0].arguments;
const idFieldName = TableSchema.id.keyPath;
//await this.getActions(TableSchema.name, config).update(argsToUpdate)
const idValue = argsToUpdate[idFieldName];
if (idValue) {
await this.getActions(TableSchema.name, config).update(argsToUpdate);
}
else {
await this.getActions(TableSchema.name, config).update(argsToUpdate, idValue);
}
return {
queryId
};
}
},
delete: async (methods) => {
if (methods[methods.length - 1].methodName == 'delete' &&
methods[methods.length - 1].arguments == null) {
const customMethods = Object.create(methods);
customMethods[methods.length - 1].methodName = 'execute';
const result = await this.requestHandler(TableSchema, config, queryId).select(customMethods);
const rows = result.value;
for (let row of rows) {
const id = row[TableSchema.id.keyPath];
await this.getActions(TableSchema.name, config).deleteByID(id);
}
return {
queryId
};
}
else if (methods[methods.length - 1].methodName == 'delete' &&
typeof methods[methods.length - 1].arguments == 'object') {
const IdInObject = methods[methods.length - 1].arguments;
const idValue = IdInObject[TableSchema.id.keyPath];
return {
queryId: queryId,
value: await this.getActions(TableSchema.name, config).deleteByID(idValue)
};
}
else if (methods[methods.length - 1].methodName == 'delete' &&
methods[methods.length - 1].arguments == '*') {
return {
queryId: queryId,
value: await this.getActions(TableSchema.name, config).deleteAll()
};
}
},
insert: async (methods) => {
const createdObjKeys = [];
const rows = methods[0].arguments;
for (let insert of rows) {
const id = await this.getActions(TableSchema.name, config).add(insert);
insert[TableSchema.id.keyPath] = id;
}
// return first element
if (rows.length == 1) {
return {
queryId: queryId,
value: rows[0]
};
}
else {
return {
queryId: queryId,
value: rows
};
}
}
};
};
}
validateStore(db, storeName) {
return db.objectStoreNames.contains(storeName);
}
validateBeforeTransaction(db, storeName, reject) {
if (!db) {
reject("Queried before opening connection");
}
if (!this.validateStore(db, storeName)) {
reject(`Store ${storeName} not found`);
}
}
createTransaction(db, dbMode, currentStore, resolve, reject, abort) {
let tx = db.transaction(currentStore, dbMode);
tx.onerror = reject;
tx.oncomplete = resolve;
tx.onabort = abort;
return tx;
}
migrate(config) {
return new IndexedDBConnection().migrate(config);
}
getConnection(config) {
return new IndexedDBConnection().connect(config);
}
}
export const indexedDB = new _indexedDB();
-2
View File
@@ -1,2 +0,0 @@
export declare type actionParam = 'insert' | 'update' | 'delete' | 'select';
export declare type dbType = 'indexedDB' | 'localStorage';
-1
View File
@@ -1 +0,0 @@
export {};
-1
View File
@@ -1 +0,0 @@
export {};
-26
View File
@@ -1,26 +0,0 @@
import { indexedDB } from './indexedDb/indexedb.js';
onmessage = async (oEvent) => {
const { TableSchema, DBconfig, queryId, action, arg } = oEvent.data;
indexedDB.requestHandler(TableSchema, DBconfig, queryId)[action](arg).then((result) => {
try {
postMessage(result);
}
catch (error) {
postMessage({
queryId: result.queryId,
value: undefined
});
}
}).catch((result)=> {
try {
postMessage(result);
}
catch (error) {
postMessage({
queryId: result.queryId,
value: undefined
});
}
})
};
-19
View File
@@ -1,19 +0,0 @@
interface WsRegister {
type?: 'response' | 'Register';
func: Function;
queryId?: string;
params: any;
method: 'execute' | 'migrate';
}
export declare class _IndexedDBWorkerQueue {
private myWorker;
webWorkerModuleSupport: boolean;
constructor();
supportsWorkerType(): boolean;
private workerQueues;
register(data: WsRegister): string | false;
onmessage(data: any): Promise<void>;
requestHandler(): void;
}
export declare const IndexedDBWorkerQueue: _IndexedDBWorkerQueue;
export {};
-51
View File
@@ -1,51 +0,0 @@
export class _IndexedDBWorkerQueue {
constructor() {
this.webWorkerModuleSupport = false;
this.workerQueues = {};
this.webWorkerModuleSupport = this.supportsWorkerType();
if (this.webWorkerModuleSupport) {
this.myWorker = new Worker(new URL('./worker.js', import.meta.url), { type: "module" });
this.myWorker.onmessage = (oEvent) => {
const data = oEvent.data;
this.onmessage(data);
};
this.myWorker.onerror = (error) => {
console.log(error, 'erroror');
};
}
}
// https://stackoverflow.com/a/62963963/14115342
supportsWorkerType() {
let supports = false;
const tester = {
get type() { return supports = true; } // it's been called, it's supported
};
try {
const worker = new Worker('blob://', tester);
}
finally {
return supports;
}
}
register(data) {
try {
this.myWorker.postMessage(data.params);
this.workerQueues[data.queryId] = data;
return data.queryId;
}
catch (error) {
return false;
}
}
async onmessage(data) {
for (const [key, value] of Object.entries(this.workerQueues)) {
const dontRepeat = await value.func(data);
if (dontRepeat || !data.queryId) {
delete this.workerQueues[key];
}
}
}
requestHandler() {
}
}
export const IndexedDBWorkerQueue = new _IndexedDBWorkerQueue();
-29
View File
@@ -1,29 +0,0 @@
import { Model } from './models/model.js';
import { LocalStorage } from './models/model.js';
import { ModelReader } from './models/model.reader.js';
import { registerModel, migrate } from './models/register-model.js';
export declare const models: {
Value(arg: any): {};
CharField(data?: import("./models/field/interface.js").CharFieldParams): import("./models/field/allFields.js").CharField;
BooleanField(data?: import("./models/field/interface.js").BooleanFieldParams): import("./models/field/allFields.js").BooleanField;
TextField(data?: import("./models/field/interface.js").TextFieldParams): import("./models/field/allFields.js").TextField;
IntegerField(data?: import("./models/field/interface.js").IntegerFieldParams): import("./models/field/allFields.js").IntegerField;
DateField(data?: import("./models/field/interface.js").DateFieldParams): import("./models/field/allFields.js").DateField;
DateTimeField(data?: import("./models/field/interface.js").DateTimeFieldParams): import("./models/field/allFields.js").DateTimeField;
BigIntegerField(data?: import("./models/field/interface.js").BigIntegerFieldParams): import("./models/field/allFields.js").BigIntegerField;
AutoField(data?: import("./models/field/interface.js").AutoFieldParams): import("./models/field/allFields.js").AutoField;
OneToOneField(data: import("./models/field/interface.js").OneToOneFieldParams): import("./models/field/allFields.js").OneToOneField;
ForeignKey(data: import("./models/field/interface.js").ForeignKeyParams): import("./models/field/allFields.js").ForeignKey;
ManyToManyField(data?: import("./models/field/interface.js").ManyToManyFieldParams): import("./models/field/allFields.js").ManyToManyField;
indexedDB: {
fields: {
JsonField: (data?: import("./models/field/interface.js").IndexedDBJsonFieldParams) => import("./models/field/allFields.js").indexedDBJsonField;
ArrayField: (data?: import("./models/field/interface.js").IndexedDBArrayFieldParams) => import("./models/field/allFields.js").indexedDBArrayField;
};
};
Model: typeof Model;
LocalStorage: typeof LocalStorage;
read: typeof ModelReader.read;
migrate: typeof migrate;
register: typeof registerModel.register;
};
-11
View File
@@ -1,11 +0,0 @@
import { Model } from './models/model.js';
import { LocalStorage } from './models/model.js';
import * as Fields from './models/field/fields.js';
import { ModelReader } from './models/model.reader.js';
import { registerModel, migrate } from './models/register-model.js';
export const models = Object.assign(Object.assign({ Model,
LocalStorage, read: ModelReader.read, migrate: migrate, register: registerModel.register }, Fields), { Value(arg) {
if (arg == 'null') {
return {};
}
} });
-140
View File
@@ -1,140 +0,0 @@
import { FieldType } from '../../sql/query/interface.js';
import { field } from './field.js';
import { FieldKeys } from './fields.interface.js';
import { AutoFieldParams, BooleanFieldParams, DateFieldParams, DateTimeFieldParams, ForeignKeyParams, IndexedDBArrayFieldParams, IndexedDBJsonFieldParams, IntegerFieldParams, ManyToManyFieldParams, OneToOneFieldParams } from './interface.js';
import { BigIntegerFieldParams } from './interface.js';
import { CharFieldParams } from './interface.js';
import { TextFieldParams } from './interface.js';
export declare class AutoField extends field {
fieldName: FieldKeys;
unique: boolean;
autoIncrement: boolean;
primaryKey?: boolean;
type: FieldType;
blank: boolean;
default?: any;
constructor(data?: AutoFieldParams);
valid(value: any): boolean;
}
export declare class BigIntegerField extends field {
fieldName: FieldKeys;
unique?: boolean;
primaryKey?: boolean;
blank?: boolean;
default?: any;
type: FieldType;
constructor(data?: BigIntegerFieldParams);
valid(value: any): boolean;
}
export declare class BooleanField extends field {
fieldName: FieldKeys;
unique?: boolean;
blank?: boolean;
default?: any;
constructor(data?: BooleanFieldParams);
valid(value: any): boolean;
}
export declare class CharField extends field {
fieldName: FieldKeys;
maxLength?: number | undefined;
minLength?: number | undefined;
choices?: any[] | undefined;
primaryKey?: boolean;
blank?: boolean;
default?: any;
unique?: boolean;
type: FieldType;
constructor(data?: CharFieldParams);
valid(value: any): boolean;
}
export declare class DateField extends field {
fieldName: FieldKeys;
type: FieldType;
blank?: boolean;
default?: any;
constructor(data?: DateFieldParams);
valid(value: any): boolean;
}
export declare class DateTimeField extends field {
fieldName: FieldKeys;
type: FieldType;
blank?: boolean;
default?: any;
constructor(data?: DateTimeFieldParams);
valid(value: any): boolean;
}
export declare class indexedDBArrayField extends field {
fieldName: FieldKeys;
type: FieldType;
blank?: boolean;
default?: any;
maxLength?: number;
minLength?: number;
size?: number;
private _field?;
get field(): any;
set field(value: any);
constructor(data?: IndexedDBArrayFieldParams);
valid(value: any): boolean;
}
export declare class indexedDBJsonField extends field {
fieldName: FieldKeys;
type: FieldType;
blank?: boolean;
default?: any;
null?: boolean;
constructor(data?: IndexedDBJsonFieldParams);
valid(value: any): boolean;
}
export declare class TextField extends field {
fieldName: FieldKeys;
maxLength?: number | undefined;
minLength?: number | undefined;
primaryKey?: boolean;
blank?: boolean;
default?: any;
type: FieldType.TEXT;
constructor(data?: TextFieldParams);
valid(value: any): boolean;
}
export declare class IntegerField extends field {
fieldName: FieldKeys;
unique?: boolean;
primaryKey?: boolean;
type: FieldType;
blank?: boolean;
default?: any;
constructor(data?: IntegerFieldParams);
valid(value: any): boolean;
}
export declare class ForeignKey extends field {
fieldName: FieldKeys;
model: any;
foreignKey: boolean;
blank?: boolean;
default?: any;
constructor(data?: ForeignKeyParams);
valid(value: any): boolean;
}
export declare class OneToOneField extends field {
fieldName: FieldKeys;
foreignKey: boolean;
model: any;
blank?: boolean;
default?: any;
onDelete?: any;
constructor(data?: OneToOneFieldParams);
contractor(contractor: any): void;
valid(value: any): boolean;
}
export declare class ManyToManyField extends field {
fieldName: FieldKeys;
model: any;
foreignKey: boolean;
blank?: boolean;
default?: any;
onDelete?: any;
unique?: boolean;
constructor(data?: ManyToManyFieldParams);
valid(value: any): boolean;
}
-253
View File
@@ -1,253 +0,0 @@
import { FieldType } from '../../sql/query/interface.js';
import { field } from './field.js';
export class AutoField extends field {
constructor(data) {
super();
this.fieldName = 'AutoField';
this.unique = true;
this.autoIncrement = true;
this.type = FieldType.BIGINT;
this.blank = true;
Object.assign(this, data);
}
valid(value) {
if (!(typeof value == 'bigint' || typeof value == 'number')) {
return false;
}
else if (!((this === null || this === void 0 ? void 0 : this.blank) == undefined && this.isNull(value) == false)) {
return false;
}
return false;
}
}
export class BigIntegerField extends field {
constructor(data) {
super();
this.fieldName = 'BigIntegerField';
this.type = FieldType.BIGINT;
Object.assign(this, data);
}
valid(value) {
if (!(typeof value == 'bigint' || typeof value == 'number')) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
else if (!(value === null || value === undefined)) {
return false;
}
}
else if (!this.rules(this, value)) {
return false;
}
return true;
}
}
export class BooleanField extends field {
constructor(data) {
super();
this.fieldName = 'BooleanField';
Object.assign(this, data);
}
valid(value) {
if (typeof value != 'boolean') {
return false;
}
return true;
}
}
export class CharField extends field {
constructor(data) {
super();
this.fieldName = 'CharField';
this.type = FieldType.DATE;
Object.assign(this, data);
}
valid(value) {
if (!(typeof value == 'string')) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
else if (!(value === null || value === undefined)) {
return false;
}
}
else if (!this.rules(this, value)) {
return false;
}
return true;
}
}
export class DateField extends field {
constructor(data) {
super();
this.fieldName = 'DateField';
this.type = FieldType.DATE;
Object.assign(this, data);
}
valid(value) {
if (!(typeof value == 'string')) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
}
else if (!((this === null || this === void 0 ? void 0 : this.blank) == undefined && this.isNull(value) == false)) {
return true;
}
return false;
}
}
export class DateTimeField extends field {
constructor(data) {
super();
this.fieldName = 'DateTimeField';
this.type = FieldType.DATE;
Object.assign(this, data);
}
valid(value) {
if (!(typeof value == 'string')) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
}
else if (!((this === null || this === void 0 ? void 0 : this.blank) == undefined && this.isNull(value) == false)) {
return false;
}
return true;
}
}
export class indexedDBArrayField extends field {
constructor(data) {
super();
this.fieldName = 'indexedDBArrayField';
this.type = FieldType.ARRAY;
Object.assign(this, data);
}
get field() {
return this._field;
}
set field(value) {
this._field = value;
}
valid(value) {
if (!(Array.isArray(value))) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
}
else if (this.isNull(value) == true) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
}
else if (this.size) {
if (value.length != this.size) {
return false;
}
}
if (this.field) {
for (const e of value) {
if (!this.field.valid(e)) {
return false;
}
}
}
return true;
}
}
export class indexedDBJsonField extends field {
constructor(data) {
super();
this.fieldName = 'indexedDBJsonField';
this.type = FieldType.JSON;
Object.assign(this, data);
}
valid(value) {
if (!(typeof value == 'object' && Array.isArray(value) == false)) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
}
else if (this.isNull(value) == true) {
}
return true;
}
}
export class TextField extends field {
constructor(data) {
super();
this.fieldName = 'TextField';
Object.assign(this, data);
}
valid(value) {
if (!(typeof value == 'string')) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
else if (!(value === null || value === undefined)) {
return false;
}
}
else if (!this.rules(this, value)) {
return false;
}
return true;
}
}
export class IntegerField extends field {
constructor(data) {
super();
this.fieldName = 'IntegerField';
this.type = FieldType.INT;
Object.assign(this, data);
}
valid(value) {
if (!(typeof value == 'number')) {
if ((this === null || this === void 0 ? void 0 : this.blank) != true) {
return false;
}
else if (!(value === null || value === undefined)) {
return false;
}
}
else if (!this.rules(this, value)) {
return false;
}
return true;
}
}
export class ForeignKey extends field {
constructor(data) {
super();
this.fieldName = 'ForeignKey';
this.foreignKey = true;
Object.assign(this, data);
}
valid(value) {
return !this.isNull(value);
}
}
export class OneToOneField extends field {
constructor(data) {
super();
this.fieldName = 'ManyToManyField';
this.foreignKey = true;
Object.assign(this, data);
}
contractor(contractor) {
throw new Error('Method not implemented.');
}
valid(value) {
return !this.isNull(value);
}
}
export class ManyToManyField extends field {
constructor(data) {
super();
this.fieldName = 'ManyToManyField';
this.foreignKey = true;
Object.assign(this, data);
}
valid(value) {
return !this.isNull(value);
}
}
-17
View File
@@ -1,17 +0,0 @@
import { FieldKeys } from "./fields.interface";
export declare class field {
fieldName: FieldKeys;
primaryKey?: any;
maxLength?: number | undefined;
minLength?: number | undefined;
choices?: any[] | undefined;
type: number;
blank?: boolean;
default?: any;
unique?: boolean;
foreignKey?: boolean;
model?: field;
get field(): boolean;
isNull(value: any): boolean;
rules(field: field, value: any): boolean;
}
-32
View File
@@ -1,32 +0,0 @@
export class field {
get field() {
return true;
}
isNull(value) {
if (value == undefined) {
return true;
}
else if (value == null) {
return true;
}
else if (value == '' && !Array.isArray(value)) {
return true;
}
return false;
}
rules(field, value) {
if (field === null || field === void 0 ? void 0 : field.maxLength) {
if (value.toString().length > field.maxLength) {
return false;
}
}
if (field === null || field === void 0 ? void 0 : field.minLength) {
if (value.toString().length < field.minLength) {
return false;
}
}
if (field === null || field === void 0 ? void 0 : field.foreignKey) {
}
return true;
}
}
-19
View File
@@ -1,19 +0,0 @@
import { AutoFieldParams, BigIntegerFieldParams, BooleanFieldParams, CharFieldParams, DateFieldParams, DateTimeFieldParams, ForeignKeyParams, IndexedDBArrayFieldParams, IndexedDBJsonFieldParams, IntegerFieldParams, ManyToManyFieldParams, OneToOneFieldParams, TextFieldParams } from './interface.js';
import * as Fields from './allFields.js';
export declare function CharField(data?: CharFieldParams): Fields.CharField;
export declare function BooleanField(data?: BooleanFieldParams): Fields.BooleanField;
export declare function TextField(data?: TextFieldParams): Fields.TextField;
export declare function IntegerField(data?: IntegerFieldParams): Fields.IntegerField;
export declare function DateField(data?: DateFieldParams): Fields.DateField;
export declare function DateTimeField(data?: DateTimeFieldParams): Fields.DateTimeField;
export declare function BigIntegerField(data?: BigIntegerFieldParams): Fields.BigIntegerField;
export declare function AutoField(data?: AutoFieldParams): Fields.AutoField;
export declare const indexedDB: {
fields: {
JsonField: (data?: IndexedDBJsonFieldParams) => Fields.indexedDBJsonField;
ArrayField: (data?: IndexedDBArrayFieldParams) => Fields.indexedDBArrayField;
};
};
export declare function OneToOneField(data: OneToOneFieldParams): Fields.OneToOneField;
export declare function ForeignKey(data: ForeignKeyParams): Fields.ForeignKey;
export declare function ManyToManyField(data?: ManyToManyFieldParams): Fields.ManyToManyField;
-10
View File
@@ -1,10 +0,0 @@
export declare const FieldKeysArray: readonly ["CharField", "JsonField", "AutoField", "BigIntegerField", "DateField", "IntegerField", "TextField", "BooleanField", "OneToOneField", "ForeignKey", "ManyToManyField", "indexedDBJsonField", "indexedDBArrayField", "DateTimeField", "DateField"];
export declare const AttributesArray: readonly ["maxLength", "minLength", "choices", "primaryKey", "unique", "autoIncrement", "type", "choices", "model", "blank", "default", "onDelete", "foreignKey"];
export declare type FieldKeys = typeof FieldKeysArray[number];
export declare type FieldsMap<K extends string | number | symbol, T> = {
[P in K]?: T;
};
export declare type FieldAttributesKeys = typeof AttributesArray[number];
export declare type AttributesMap<K extends string | number | symbol, T> = {
[P in K]?: T;
};
@@ -1,33 +0,0 @@
export const FieldKeysArray = [
'CharField',
'JsonField',
'AutoField',
'BigIntegerField',
'DateField',
'IntegerField',
'TextField',
'BooleanField',
'OneToOneField',
'ForeignKey',
'ManyToManyField',
'indexedDBJsonField',
'indexedDBArrayField',
'DateTimeField',
'DateField'
]; // TS3.4 syntax
export const AttributesArray = [
'maxLength',
'minLength',
'choices',
'primaryKey',
'unique',
'autoIncrement',
'type',
'choices',
'model',
'blank',
'default',
'onDelete',
'foreignKey'
]; // TS3.4 syntax
// https://stackoverflow.com/a/64694571/14115342
-40
View File
@@ -1,40 +0,0 @@
import * as Fields from './allFields.js';
export function CharField(data) {
return new Fields.CharField(data);
}
export function BooleanField(data) {
return new Fields.BooleanField(data);
}
export function TextField(data) {
return new Fields.TextField(data);
}
export function IntegerField(data) {
return new Fields.IntegerField(data);
}
export function DateField(data) {
return new Fields.DateField(data);
}
export function DateTimeField(data) {
return new Fields.DateTimeField(data);
}
export function BigIntegerField(data) {
return new Fields.BigIntegerField(data);
}
export function AutoField(data) {
return new Fields.AutoField(data);
}
export const indexedDB = {
fields: {
JsonField: (data) => new Fields.indexedDBJsonField(data),
ArrayField: (data) => new Fields.indexedDBArrayField(data)
}
};
export function OneToOneField(data) {
return new Fields.OneToOneField(data);
}
export function ForeignKey(data) {
return new Fields.ForeignKey(data);
}
export function ManyToManyField(data) {
return new Fields.ManyToManyField(data);
}
-97
View File
@@ -1,97 +0,0 @@
import { field } from './field.js';
export interface CharFieldParams {
maxLength?: number;
minLength?: number;
primaryKey?: boolean;
choices?: any[] | undefined;
unique?: boolean;
blank?: boolean;
default?: any;
}
export interface TextFieldParams {
maxLength?: number;
minLength?: number;
primaryKey?: boolean;
unique?: boolean;
default?: any;
blank?: boolean;
}
export interface IntegerFieldParams {
primaryKey?: boolean;
unique?: boolean;
default?: any;
blank?: boolean;
}
export interface BigIntegerFieldParams {
primaryKey?: boolean;
unique?: boolean;
default?: any;
blank?: boolean;
}
export interface AutoFieldParams {
primaryKey?: boolean;
}
export interface IndexedDBJsonFieldParams {
unique?: boolean;
blank?: boolean;
null?: boolean;
default?: any;
}
export interface IndexedDBArrayFieldParams {
unique?: boolean;
blank?: boolean;
type?: any;
default?: any;
maxLength?: number;
minLength?: number;
field?: field;
size?: number;
}
export interface DateTimeFieldParams {
unique?: boolean;
blank?: boolean;
default?: any;
}
export interface DateFieldParams {
unique?: boolean;
blank?: boolean;
default?: any;
}
export interface BooleanFieldParams {
unique?: boolean;
blank?: boolean;
default?: any;
}
export interface ForeignKeyParams {
model: any;
unique?: boolean;
blank?: boolean;
default?: any;
onDelete?: any;
primaryKey?: boolean;
}
export interface OneToOneFieldParams {
model: any;
unique?: boolean;
blank?: boolean;
default?: any;
onDelete?: any;
}
export interface ManyToManyFieldParams {
model: any;
unique?: boolean;
blank?: boolean;
default?: any;
onDelete?: any;
}
export interface PossibleFieldAttributes {
model?: any;
unique?: boolean;
blank?: boolean;
default?: any;
onDelete?: any;
primaryKey?: boolean;
maxLength?: number;
minLength?: number;
choices?: any[] | undefined;
}
-1
View File
@@ -1 +0,0 @@
export {};
-8
View File
@@ -1,8 +0,0 @@
export declare class _ModelMigrations {
callback: any[];
private isMigrationsReady;
migrationsState(value: boolean): void;
isReady(modelClassRepresentation: any): void;
waitMigration(): Promise<unknown>;
}
export declare const ModelMigrations: _ModelMigrations;
-31
View File
@@ -1,31 +0,0 @@
export class _ModelMigrations {
constructor() {
this.callback = [];
this.isMigrationsReady = false;
}
migrationsState(value) {
this.isMigrationsReady = value;
if (this.isMigrationsReady) {
this.callback.forEach((item, index, object) => {
item();
object.splice(index, 1);
});
}
}
isReady(modelClassRepresentation) {
// const classInstance: typeof models.Model = new modelClassRepresentation()
}
async waitMigration() {
return new Promise((resolve, reject) => {
if (!this.isMigrationsReady) {
this.callback.push(() => {
resolve('ready');
});
}
else {
resolve('ready');
}
});
}
}
export const ModelMigrations = new _ModelMigrations();
View File
View File
-14
View File
@@ -1,14 +0,0 @@
import { Methods, Method } from './model.interface.js';
import { DatabaseSchema, TableSchema } from './register-modal.interface.js';
export declare class ModelManager {
constructor();
static obj: (DatabaseSchema: DatabaseSchema, TableSchema: TableSchema) => {
create: (arg: Method[], queryId: string) => Promise<any>;
get: (arg: Method[], queryId: string) => Promise<any>;
save: (arg: Method[], queryId: string) => Promise<any>;
execute: (arg: Methods | Method[], queryId: string) => Promise<any>;
update: (arg: any, queryId: string) => Promise<any>;
delete: (arg: any, queryId: string) => Promise<any>;
all: (arg: any, queryId: string) => Promise<any>;
};
}
-39
View File
@@ -1,39 +0,0 @@
var _a;
import { DBSwitch } from '../connection/dbSwtich.js';
import { ModelMigrations } from './mode-migrations.js';
export class ModelManager {
constructor() { }
}
_a = ModelManager;
ModelManager.obj = (DatabaseSchema, TableSchema) => {
return {
create: async (arg, queryId) => {
await ModelMigrations.waitMigration();
return await DBSwitch.requestHandler(TableSchema, DatabaseSchema, DatabaseSchema.type, 'insert', arg, queryId);
},
get: async (arg, queryId) => {
await ModelMigrations.waitMigration();
return await DBSwitch.requestHandler(TableSchema, DatabaseSchema, DatabaseSchema.type, 'select', arg, queryId);
},
save: async (arg, queryId) => {
await ModelMigrations.waitMigration();
return await DBSwitch.requestHandler(TableSchema, DatabaseSchema, DatabaseSchema.type, 'update', arg, queryId);
},
execute: async (arg, queryId) => {
await ModelMigrations.waitMigration();
return await DBSwitch.requestHandler(TableSchema, DatabaseSchema, DatabaseSchema.type, 'select', arg, queryId);
},
update: async (arg, queryId) => {
await ModelMigrations.waitMigration();
return await DBSwitch.requestHandler(TableSchema, DatabaseSchema, DatabaseSchema.type, 'update', arg, queryId);
},
delete: async (arg, queryId) => {
await ModelMigrations.waitMigration();
return await DBSwitch.requestHandler(TableSchema, DatabaseSchema, DatabaseSchema.type, 'delete', arg, queryId);
},
all: async (arg, queryId) => {
await ModelMigrations.waitMigration();
return await DBSwitch.requestHandler(TableSchema, DatabaseSchema, DatabaseSchema.type, 'select', arg, queryId);
},
};
};
-64
View File
@@ -1,64 +0,0 @@
import { getParams } from './model.interface.js';
import { DatabaseSchema, DatabaseSchemaLocalStorage, TableSchema } from './register-modal.interface.js';
import { ModelManager } from './model-manager.js';
export declare class Model extends ModelManager {
constructor(obg?: any);
get(arg: any): Promise<any>;
getDBSchema(): DatabaseSchema;
getModelName(): string;
filter(...arg: any[]): any;
getTableSchema(): TableSchema;
getPrimaryKeyValue(): any;
save(): Promise<void>;
delete(): Promise<void>;
static deleteAll(): Promise<void>;
all(): Promise<any>;
getFields(arg: any): {};
formValidation(data: any): boolean;
Value(args: any): string;
static Value(args: any): string;
static formValidation(data: any): boolean;
static getModelsFields(arg: any): Promise<void>;
static all(): Promise<any>;
static get(arg: getParams): Promise<any>;
private static getId;
static getModelName(): string;
static filter(...arg: any[]): any;
static NewModelInstance(): any;
static getDBSchema(): DatabaseSchema;
static getTableSchema(): TableSchema;
private static getEmptyFields;
private static getFields;
static create(arg: any): Promise<any>;
private static newInstance;
static createOrFind(getArg: any, defaultCreate: any): Promise<any[]>;
static updateOrCreate(argToFind: any, argsToUpdate: any): Promise<any>;
static update(arg: any): Promise<any>;
static object: ({ queryId, DBconfig, TableSchema, some }: {
queryId?: string;
DBconfig: any;
TableSchema: any;
some?: any;
}) => {
filter: (...args: any[]) => any;
execute: () => Promise<any>;
update: (args: any) => Promise<any>;
delete: () => Promise<any>;
all: () => Promise<any>;
};
}
export declare class LocalStorage {
constructor();
static save(data?: Object): void;
static get(): any;
static getModelName(): string;
static getDBSchema(): DatabaseSchemaLocalStorage;
static getTableSchema(): TableSchema;
private static getIgnoreAttributes;
static ignoreAttributes(attributesStartWidth?: string[]): void;
private static getFields;
private static formValidation;
static clear(): void;
static clearComponent(): void;
static clearStorage(): void;
}
-10
View File
@@ -1,10 +0,0 @@
export declare const MethodNameArray: readonly ["save", "filter", "get", "create", "execute", "update", "delete", "all", "first"];
export declare type MethodName = typeof MethodNameArray[number];
export interface Method {
methodName: MethodName;
arguments: any;
}
export declare type Methods = {
[key: string]: Method[];
};
export declare type getParams = Object;
-11
View File
@@ -1,11 +0,0 @@
export const MethodNameArray = [
'save',
'filter',
'get',
'create',
'execute',
'update',
'delete',
'all',
'first',
]; // TS3.4 syntax
-393
View File
@@ -1,393 +0,0 @@
var _a, _b;
import { hashCode, uniqueGenerator } from '../utils.js';
import { ModelManager } from './model-manager.js';
import { models, modelsConfig, modelsConfigLocalStorage } from './register-model.js';
import { FieldType } from '../sql/query/interface.js';
import * as Fields from './field/allFields.js';
let methods = {} = {};
// inspire by https://github.com/brianschardt/browser-orm
export class Model extends (_b = ModelManager) {
constructor(obg) {
super();
Object.assign(this, obg);
}
get(arg) {
return Model.get(arg);
}
getDBSchema() {
const modelName = this.constructor.name;
return modelsConfig[modelName].DatabaseSchema;
}
getModelName() {
return this.constructor.name;
}
filter(...arg) {
return Model.filter(arg);
}
getTableSchema() {
const modelName = this.constructor.name;
return modelsConfig[modelName].TableSchema;
}
getPrimaryKeyValue() {
const TableSchema = this.getTableSchema();
const idFieldName = TableSchema.id.keyPath;
return this[idFieldName];
}
async save() {
const DBconfig = this.getDBSchema();
const tableSchema = this.getTableSchema();
const fiendsName = tableSchema.fields.map((field) => field.name);
fiendsName.push(tableSchema.id.keyPath);
const Fields = {};
for (let name of fiendsName) {
Fields[name] = this[name];
}
const methods = [{ methodName: 'save', arguments: Fields }];
const queryId = uniqueGenerator();
await Model.obj(DBconfig, tableSchema).save(methods, queryId);
}
async delete() {
const DBconfig = this.getDBSchema();
const TableSchema = this.getTableSchema();
const idFieldName = TableSchema.id.keyPath;
const createArg = {};
createArg[idFieldName] = this[idFieldName];
const _methods = [{ methodName: 'delete', arguments: createArg }];
const queryId = uniqueGenerator();
await Model.obj(DBconfig, TableSchema).delete(_methods, queryId);
}
static async deleteAll() {
const DBconfig = this.getDBSchema();
const TableSchema = this.getTableSchema();
const idFieldName = TableSchema.id.keyPath;
const createArg = {};
createArg[idFieldName] = this[idFieldName];
const _methods = [{ methodName: 'delete', arguments: '*' }];
const queryId = uniqueGenerator();
await Model.obj(DBconfig, TableSchema).delete(_methods, queryId);
}
async all() {
const DBconfig = this.getDBSchema();
const TableSchema = this.getTableSchema();
return await Model.object({ DBconfig, TableSchema }).all();
}
getFields(arg) {
return Model.getFields(arg);
}
formValidation(data) {
return Model.formValidation(data);
}
Value(args) {
return Model.Value(args);
}
static Value(args) {
return '';
}
static formValidation(data) {
const TableSchema = this.getTableSchema();
for (let field of TableSchema.fields) {
const Field = new Fields[field.className](field.fieldAttributes);
const FieldValue = data[field.name];
if (!Field.valid(FieldValue)) {
throw ('invalid insert into ' + TableSchema.name + ', invalid value for field ' + field.name + ' = ' + JSON.stringify(FieldValue));
}
}
return true;
}
static async getModelsFields(arg) {
var _c;
const newArgs = {};
const TableSchema = this.getTableSchema();
if ((_c = TableSchema.id) === null || _c === void 0 ? void 0 : _c.autoIncrement) {
TableSchema.fields.push({
keyPath: TableSchema.id.keyPath,
name: TableSchema.id.keyPath,
options: {
type: FieldType.INT,
unique: true
}
});
}
for (const fieldName in TableSchema.fields) {
newArgs[fieldName] = arg[fieldName];
}
}
static async all() {
const DBconfig = this.getDBSchema();
const TableSchema = this.getTableSchema();
return await Model.object({ DBconfig, TableSchema }).all();
}
static async get(arg) {
const _methods = [{ methodName: 'get', arguments: arg }];
const DBconfig = this.getDBSchema();
const TableSchema = this.getTableSchema();
const queryId = uniqueGenerator();
const foundObj = await super.obj(DBconfig, TableSchema).get(_methods, queryId);
if (!foundObj) {
return false;
}
const ModelName = this.getModelName();
let newInstance = new models[ModelName]();
Object.assign(newInstance, Object.assign({}, foundObj));
if (TableSchema.fieldTypes['ManyToManyField']) {
for (const fieldName of TableSchema.fieldTypes['ManyToManyField']) {
delete newInstance[fieldName];
}
}
Object.defineProperty(newInstance, TableSchema.id.keyPath, {
configurable: false,
writable: false
});
delete newInstance.obj;
return newInstance;
}
static getId() {
return hashCode(this.toString());
}
static getModelName() {
return this.toString().split('(' || /s+/)[0].split(' ' || /s+/)[1];
}
static filter(...arg) {
const queryId = uniqueGenerator();
const DBconfig = this.getDBSchema();
const TableSchema = this.getTableSchema();
const newInstanceModel = this.NewModelInstance();
return Object.assign(newInstanceModel, this.object({ queryId, DBconfig, TableSchema, some: ['filter', arg] }));
}
static NewModelInstance() {
class newInstanceModel {
}
Object.assign(newInstanceModel, this);
return newInstanceModel;
}
static getDBSchema() {
const modalName = this.getModelName();
return modelsConfig[modalName].DatabaseSchema;
}
static getTableSchema() {
const modalName = this.getModelName();
return modelsConfig[modalName].TableSchema;
}
static async getEmptyFields() {
const TableSchema = this.getTableSchema();
const emptyFields = {};
const fieldsName = TableSchema.fields.map((field) => field.name);
for (let fieldName of fieldsName) {
emptyFields[fieldName] = null;
}
return emptyFields;
}
static getFields(arg) {
const TableSchema = this.getTableSchema();
const filteredArgs = {};
const fieldsName = TableSchema.fields.map((field) => field.name);
for (let fieldName of fieldsName) {
if (arg.hasOwnProperty(fieldName)) {
filteredArgs[fieldName] = arg[fieldName];
}
}
return filteredArgs;
}
static async create(arg) {
if (arg.constructor.name != 'Array') {
arg = [arg];
}
const emptyFields = await this.getEmptyFields();
const TableSchema = this.getTableSchema();
for (let i in arg) {
arg[i] = Object.assign(Object.assign({}, emptyFields), this.getFields(arg[i]));
if (!this.formValidation(arg[i])) {
throw ('invalid ' + JSON.stringify(arg[i]));
}
}
for (let i in arg) {
if (TableSchema.attributes.foreignKey) {
for (let field of TableSchema.attributes.foreignKey) {
try {
arg[i][field] = arg[i][field].getPrimaryKeyValue();
}
catch (error) { }
}
}
}
const _methods = [{ methodName: 'create', arguments: arg }];
const DBconfig = this.getDBSchema();
const queryId = uniqueGenerator();
const createObject = await super.obj(DBconfig, TableSchema).create(_methods, queryId);
if (createObject) {
if (typeof createObject[TableSchema.id.keyPath] == 'object') {
throw (createObject[TableSchema.id.keyPath].error);
}
else {
const ModelName = this.getModelName();
let newInstance = new models[ModelName]();
Object.assign(newInstance, createObject);
delete newInstance.obj;
return newInstance;
}
}
else {
}
}
static newInstance({ TableSchema, DBconfig, ModelName, dataToMerge }) {
let newInstance = new models[ModelName]();
Object.assign(newInstance, Object.assign({}, dataToMerge));
delete newInstance.obj;
return newInstance;
}
static async createOrFind(getArg, defaultCreate) {
const result = await this.filter(getArg).execute();
const TableSchema = this.getTableSchema();
const DBconfig = this.getDBSchema();
const ModelName = this.getModelName();
let instance;
let created;
if (result.length == 1) {
created = false;
instance = await this.newInstance({ TableSchema, DBconfig, ModelName, dataToMerge: result[0] });
}
else {
created = true;
instance = await this.create(Object.assign(getArg, defaultCreate));
}
return [instance, created];
}
static async updateOrCreate(argToFind, argsToUpdate) {
let [instance, created] = await this.createOrFind(argToFind, argsToUpdate);
if (!created) {
const params = Object.assign(argToFind, argsToUpdate);
instance = Object.assign(instance, params);
await instance.save();
}
return instance;
}
static async update(arg) {
arg = this.getFields(arg);
const DBconfig = this.getDBSchema();
const TableSchema = this.getTableSchema();
const _methods = [{ methodName: 'update', arguments: arg }];
const queryId = uniqueGenerator();
return await super.obj(DBconfig, TableSchema).update(_methods, queryId);
}
}
_a = Model;
Model.object = ({ queryId = uniqueGenerator(), DBconfig, TableSchema, some = null }) => {
if (!methods[queryId]) {
methods[queryId] = [];
}
if (some) {
const methodName = some[0];
const methodArgs = some[1];
_a.object({ queryId, DBconfig, TableSchema })[methodName](...methodArgs);
}
return {
filter: (...args) => {
methods[queryId].push({ methodName: 'filter', arguments: args });
const newInstanceModel = _a.NewModelInstance();
return Object.assign(newInstanceModel, _a.object({ DBconfig, TableSchema, queryId }));
},
execute: async () => {
methods[queryId].push({ methodName: 'execute', arguments: null });
const _methods = methods[queryId];
methods[queryId] = [];
return await Reflect.get(_b, "obj", _a).call(_a, DBconfig, TableSchema).execute(_methods, queryId);
},
update: async (args) => {
methods[queryId].push({ methodName: 'update', arguments: args });
const _methods = methods[queryId];
methods[queryId] = [];
return await Reflect.get(_b, "obj", _a).call(_a, DBconfig, TableSchema).update(_methods, queryId);
},
delete: async () => {
methods[queryId].push({ methodName: 'delete', arguments: null });
const _methods = methods[queryId];
methods[queryId] = [];
return await Reflect.get(_b, "obj", _a).call(_a, DBconfig, TableSchema).delete(_methods, queryId);
},
all: async () => {
methods[queryId].push({ methodName: 'all', arguments: null });
const _methods = methods[queryId];
methods[queryId] = [];
return await Reflect.get(_b, "obj", _a).call(_a, DBconfig, TableSchema).all(_methods, queryId);
}
};
};
export class LocalStorage {
constructor() { }
static save(data = {}) {
const dataToSave = this.getFields(Object.assign(this, Object.assign({}, data)));
const key = this.getTableSchema().id;
localStorage.setItem(key.keyPath, JSON.stringify(dataToSave));
}
static get() {
const key = this.getTableSchema().id;
const restedData = JSON.parse(localStorage.getItem(key.keyPath));
Object.assign(this, Object.assign({}, restedData));
return restedData;
}
static getModelName() {
return this.toString().split('(' || /s+/)[0].split(' ' || /s+/)[1];
}
static getDBSchema() {
const modalName = this.getModelName();
return modelsConfigLocalStorage[modalName].DatabaseSchema;
}
static getTableSchema() {
const modalName = this.getModelName();
return modelsConfigLocalStorage[modalName].TableSchema;
}
static getIgnoreAttributes() {
return false;
}
static ignoreAttributes(attributesStartWidth = []) {
if (!this.getIgnoreAttributes()) {
this.getIgnoreAttributes = () => {
return attributesStartWidth;
};
}
}
static getFields(arg) {
const TableSchema = this.getTableSchema();
const filteredArgs = {};
const fieldsName = TableSchema.fields.map((field) => field.name);
const Attributes = this.getIgnoreAttributes();
const fieldNameFilter = fieldsName.filter((fieldName) => {
if (Attributes) {
for (let Attribute of Attributes) {
if (fieldName.startsWith(Attribute)) {
return false;
}
}
}
return true;
});
for (let fieldName of fieldNameFilter) {
if (arg.hasOwnProperty(fieldName)) {
filteredArgs[fieldName] = arg[fieldName];
}
}
return filteredArgs;
}
static formValidation(data) {
const TableSchema = this.getTableSchema();
for (let field of TableSchema.fields) {
const Field = new Fields[field.className](field.fieldAttributes);
const FieldValue = data[field.name];
if (!Field.valid(FieldValue)) {
throw ('invalid insert into ' + TableSchema.name + ', invalid value for field ' + field.name + ' = ' + JSON.stringify(FieldValue));
}
}
return true;
}
static clear() {
this.clearComponent();
this.clearStorage();
}
static clearComponent() {
const key = this.getTableSchema().id;
}
static clearStorage() {
const key = this.getTableSchema().id;
localStorage.removeItem(key.keyPath);
}
}
-21
View File
@@ -1,21 +0,0 @@
import { FieldsMap, AttributesMap } from './field/fields.interface.js';
export declare class ModelReader {
static read(modelClassRepresentation: any): {
modelName: string;
fields: {
[key: string]: any;
};
fieldTypes: FieldsMap<"CharField" | "JsonField" | "AutoField" | "BigIntegerField" | "DateField" | "IntegerField" | "TextField" | "BooleanField" | "OneToOneField" | "ForeignKey" | "ManyToManyField" | "indexedDBJsonField" | "indexedDBArrayField" | "DateTimeField", string[]>;
attributes: AttributesMap<"maxLength" | "minLength" | "choices" | "primaryKey" | "unique" | "autoIncrement" | "type" | "model" | "blank" | "default" | "onDelete" | "foreignKey", string[]>;
};
}
export declare class LocalStorageModelReader {
static read(modelClassRepresentation: any): {
modelName: string;
fields: {
[key: string]: any;
};
attributes: AttributesMap<"maxLength" | "minLength" | "choices" | "primaryKey" | "unique" | "autoIncrement" | "type" | "model" | "blank" | "default" | "onDelete" | "foreignKey", string[]>;
fieldTypes: FieldsMap<"CharField" | "JsonField" | "AutoField" | "BigIntegerField" | "DateField" | "IntegerField" | "TextField" | "BooleanField" | "OneToOneField" | "ForeignKey" | "ManyToManyField" | "indexedDBJsonField" | "indexedDBArrayField" | "DateTimeField", string[]>;
};
}
-53
View File
@@ -1,53 +0,0 @@
import { FieldKeysArray } from './field/fields.interface.js';
export class ModelReader {
static read(modelClassRepresentation) {
const classInstance = new modelClassRepresentation();
const modelName = classInstance.getModelName();
const fieldTypes = {};
const fields = {};
const attributes = {};
for (const [fieldName, Field] of Object.entries(classInstance)) {
const type = Field === null || Field === void 0 ? void 0 : Field.fieldName;
if (FieldKeysArray.includes(type)) {
fields[fieldName] = Field;
if (!fieldTypes[type]) {
fieldTypes[type] = [];
}
fieldTypes[type].push(fieldName);
for (const [FieldProperty, value] of Object.entries(Field)) {
if (typeof value != "function") {
if (!attributes[FieldProperty]) {
attributes[FieldProperty] = [];
}
attributes[FieldProperty].push(fieldName);
}
}
}
}
return {
modelName,
fields,
fieldTypes,
attributes,
};
}
}
export class LocalStorageModelReader {
static read(modelClassRepresentation) {
const classInstance = modelClassRepresentation;
const fieldTypes = {};
const attributes = {};
const modelName = classInstance.getModelName();
const fields = {};
for (const [fieldName, Field] of Object.entries(classInstance)) {
// const type = Field?.fieldName
fields[fieldName] = Field || null;
}
return {
modelName,
fields,
attributes,
fieldTypes
};
}
}
-40
View File
@@ -1,40 +0,0 @@
import { Model, LocalStorage } from './model.js';
import { DatabaseSchema, DatabaseSchemaLocalStorage, TableSchema, TableSchemaLocalStorage } from './register-modal.interface.js';
import { OneToOneField, ForeignKey, ManyToManyField } from './field/allFields.js';
interface register {
databaseName: string;
version: number;
type: 'indexedDB' | 'localStorage';
models: typeof Model[] | typeof LocalStorage[];
}
export declare const models: {};
export declare const modelsConfig: {
[key: string]: {
DatabaseSchema: DatabaseSchema;
TableSchema: TableSchema;
OneToOneField?: {
[key: string]: {};
};
};
};
export declare const modelsLocalStorage: {};
export declare const modelsConfigLocalStorage: {
[key: string]: {
DatabaseSchema: DatabaseSchemaLocalStorage;
TableSchema: TableSchemaLocalStorage;
};
};
export declare function migrate(register: register): void;
export declare class registerModel {
static register(entries: register): Promise<void>;
static manyToManyRelationShip(foreignKeyField: ManyToManyField, FieldName: string, modelName: string, databaseSchema: DatabaseSchema): Model;
}
export declare class registerLocalStorage {
static register(entries: register): Promise<void>;
}
export declare class ModelEditor {
static addMethodOneToOneField(foreignKeyField: OneToOneField, FieldName: string, modelName: string, databaseSchema: DatabaseSchema): void;
static addMethodForeignKey(foreignKeyField: ForeignKey, FieldName: string, modelName: string, databaseSchema: DatabaseSchema): void;
static addMethodManyToManyField(foreignKeyField: ManyToManyField, FieldName: string, modelName: string, databaseSchema: DatabaseSchema): Promise<void>;
}
export {};
-346
View File
@@ -1,346 +0,0 @@
import { Model } from './model.js';
import { LocalStorageModelReader, ModelReader } from './model.reader.js';
import { indexedDB } from './../connection/indexedDb/indexedb.js';
import { OneToOneField, ForeignKey, ManyToManyField } from './field/allFields.js';
import { uncapitalize } from '../utils.js';
import { FieldType } from '../sql/query/interface.js';
import { ModelMigrations } from './mode-migrations.js';
export const models = {};
export const modelsConfig = {};
export const modelsLocalStorage = {};
export const modelsConfigLocalStorage = {};
export function migrate(register) {
if (register.type == 'indexedDB') {
registerModel.register(register);
}
else if (register.type == 'localStorage') {
registerLocalStorage.register(register);
}
}
export class registerModel {
static async register(entries) {
var _a, _b, _c;
const databaseSchema = {
databaseName: entries.databaseName,
version: entries.version,
type: entries.type,
stores: []
};
for (const modelClassRepresentations of entries.models) {
const ModelName = modelClassRepresentations.getModelName();
models[ModelName] = modelClassRepresentations;
}
let index = 0;
for (const modelClassRepresentations of entries.models) {
const { fields, modelName, attributes, fieldTypes } = ModelReader.read(modelClassRepresentations);
const idFieldName = (_a = attributes === null || attributes === void 0 ? void 0 : attributes.primaryKey) === null || _a === void 0 ? void 0 : _a.shift();
databaseSchema.stores.push({
name: modelName,
id: {
keyPath: idFieldName || 'id',
autoIncrement: fields[idFieldName] ? ((_b = fields[idFieldName]) === null || _b === void 0 ? void 0 : _b.primaryKey) == true : true,
type: FieldType.INT
},
attributes: attributes,
fields: [],
fieldTypes
});
for (const [fieldName, Field] of Object.entries(fields)) {
// dont register fields that is primary key and auto increment
if (!((Field === null || Field === void 0 ? void 0 : Field.primaryKey) && (Field === null || Field === void 0 ? void 0 : Field.autoIncrement)) && !((_c = fieldTypes['ManyToManyField']) === null || _c === void 0 ? void 0 : _c.includes(fieldName))) {
databaseSchema.stores[index].fields.push({
name: fieldName,
keyPath: fieldName,
options: {
unique: (Field === null || Field === void 0 ? void 0 : Field.unique) || false,
type: Field.type
},
className: Field === null || Field === void 0 ? void 0 : Field.fieldName,
fieldAttributes: Object.assign({}, Field)
});
}
if (Field instanceof OneToOneField) {
await ModelEditor.addMethodOneToOneField(Field, fieldName, modelName, databaseSchema);
}
else if (Field instanceof ForeignKey) {
await ModelEditor.addMethodForeignKey(Field, fieldName, modelName, databaseSchema);
}
else if (Field instanceof ManyToManyField) {
await ModelEditor.addMethodManyToManyField(Field, fieldName, modelName, databaseSchema);
}
}
index++;
}
for (const modelClassRepresentations of entries.models) {
const ModelName = modelClassRepresentations.getModelName();
models[ModelName] = modelClassRepresentations;
const tableSchema = databaseSchema.stores.find((e) => e.name == ModelName);
modelsConfig[ModelName] = {
DatabaseSchema: databaseSchema,
TableSchema: tableSchema
};
}
if (databaseSchema.type == 'indexedDB') {
await indexedDB.migrate(databaseSchema);
}
ModelMigrations.migrationsState(true);
}
static manyToManyRelationShip(foreignKeyField, FieldName, modelName, databaseSchema) {
const foreignKeyFieldModel = foreignKeyField.model;
const currentModel = models[modelName];
const foreignKeyFieldModelName = foreignKeyFieldModel.getModelName();
const currentModelName = models[modelName].getModelName();
const tableName = currentModelName + foreignKeyFieldModelName;
const num = databaseSchema.stores.push({
name: tableName,
id: { keyPath: 'id', autoIncrement: true, type: FieldType.INT },
fields: [
{
name: 'iD' + foreignKeyFieldModelName,
keyPath: 'iD' + foreignKeyFieldModelName,
options: {
unique: false,
type: FieldType.INT
},
className: 'IntegerField'
},
{
name: 'iD' + currentModelName,
keyPath: 'iD' + currentModelName,
options: {
unique: false,
type: FieldType.INT
},
className: 'IntegerField'
}
],
attributes: {},
fieldTypes: {
IntegerField: ['iD' + foreignKeyFieldModelName, 'iD' + currentModelName]
}
});
const id = num - 1;
models[tableName] = generateGenericModel({
DBSchema: databaseSchema,
ModelName: tableName,
TableSchema: databaseSchema.stores[id]
});
return generateGenericModel({
DBSchema: databaseSchema,
ModelName: tableName,
TableSchema: databaseSchema.stores[id]
});
}
}
export class registerLocalStorage {
static async register(entries) {
const databaseSchema = {
databaseName: entries.databaseName,
version: entries.version,
type: 'localStorage',
stores: []
};
for (const modelClassRepresentations of entries.models) {
const ModelName = modelClassRepresentations.getModelName();
modelsLocalStorage[ModelName] = modelClassRepresentations;
}
let index = 0;
for (const modelClassRepresentations of entries.models) {
const { fields, modelName, attributes, fieldTypes } = LocalStorageModelReader.read(modelClassRepresentations);
// const idFieldName = attributes?.primaryKey?.shift()
databaseSchema.stores.push({
name: modelName,
id: {
keyPath: modelName,
type: FieldType.VARCHAR,
autoIncrement: false
},
attributes: attributes,
fields: [],
fieldTypes
});
for (const [fieldName, Field] of Object.entries(fields)) {
databaseSchema.stores[index].fields.push({
name: fieldName,
keyPath: fieldName,
options: {
unique: false,
type: null
},
className: Field === null || Field === void 0 ? void 0 : Field.fieldName,
fieldAttributes: Object.assign({}, Field)
});
}
index++;
}
for (const modelClassRepresentations of entries.models) {
const ModelName = modelClassRepresentations.getModelName();
const tableSchema = databaseSchema.stores.find((e) => e.name == ModelName);
modelClassRepresentations.getDBSchema = () => {
return databaseSchema;
};
modelClassRepresentations.getTableSchema = () => {
return tableSchema;
};
modelsConfigLocalStorage[ModelName] = {
DatabaseSchema: databaseSchema,
TableSchema: tableSchema
};
modelsLocalStorage[ModelName] = modelClassRepresentations;
}
ModelMigrations.migrationsState(true);
}
}
export class ModelEditor {
static addMethodOneToOneField(foreignKeyField, FieldName, modelName, databaseSchema) {
const foreignKeyFieldModel = foreignKeyField.model;
const currentModel = models[modelName];
foreignKeyFieldModel['prototype'][modelName] = async function (body) {
const foreignModel = currentModel;
const TableSchema = foreignModel.getTableSchema();
const obj = {};
obj[TableSchema.id.keyPath] = this.getPrimaryKeyValue();
return await foreignModel.get(obj);
};
currentModel['prototype'][foreignKeyFieldModel['name']] = async function () {
const foreignModel = foreignKeyFieldModel;
let params = {};
const TableSchema = foreignModel.getTableSchema();
params[TableSchema.id.keyPath] = this.getPrimaryKeyValue();
return await foreignModel.get(params);
};
}
static addMethodForeignKey(foreignKeyField, FieldName, modelName, databaseSchema) {
const foreignKeyFieldModel = foreignKeyField.model;
const currentModel = models[modelName];
const FunctionName = uncapitalize(modelName);
foreignKeyFieldModel['prototype'][FunctionName + '_setAll'] = async function () {
const obj = {};
obj[FieldName] = this.getPrimaryKeyValue();
const currentModel = models[modelName];
return await currentModel.filter(obj).execute();
};
foreignKeyFieldModel['prototype'][FunctionName + '_setAdd'] = async function (arg) {
const reporter = this;
arg[FieldName] = reporter;
return currentModel['create'](arg);
};
currentModel['prototype'][foreignKeyFieldModel.getModelName()] = async function () {
const TableSchema = foreignKeyFieldModel.getTableSchema();
const obj = {};
obj[TableSchema.id.keyPath] = this[FieldName];
return foreignKeyFieldModel.filter(obj).execute();
};
}
static async addMethodManyToManyField(foreignKeyField, FieldName, modelName, databaseSchema) {
const foreignKeyFieldModel = foreignKeyField.model;
FieldName = FieldName;
const currentModel = models[modelName];
const middleTable = await registerModel.manyToManyRelationShip(foreignKeyField, FieldName, modelName, databaseSchema);
currentModel['prototype'][FieldName + '_add'] = async function (modelInstances) {
if (modelInstances.constructor.name != 'Array') {
modelInstances = [modelInstances];
}
for (const modelInstance of modelInstances) {
if (modelInstance instanceof foreignKeyFieldModel) {
let params = {};
params[`iD${currentModel.getModelName()}`] = this.getPrimaryKeyValue();
params[`iD${modelInstance.getModelName()}`] = modelInstance.getPrimaryKeyValue();
await middleTable['create'](params);
}
else {
throw ('Need to be instance of ' + foreignKeyFieldModel.getModelName());
}
}
};
currentModel['prototype'][FieldName] = function () {
let _model = this;
return {
async all() {
let params = {};
params[`iD${_model.getModelName()}`] = _model.getPrimaryKeyValue();
const middleTableResult = await middleTable['filter'](params).execute();
foreignKeyField.model;
return middleTableResult;
}
};
};
currentModel['prototype'][FieldName + '_all'] = async function () {
let _model = this;
let params = {};
let result = [];
params[`iD${_model.getModelName()}`] = _model.getPrimaryKeyValue();
const middleTableResult = await middleTable['filter'](params).execute();
let ids;
if (middleTableResult) {
const TableSchema = foreignKeyField.model.getTableSchema();
ids = middleTableResult.map((e) => {
return e[`iD${foreignKeyField.model.name}`];
});
let params = {};
for (const id of ids) {
try {
params[TableSchema.id.keyPath] = id;
const row = await foreignKeyField.model.get(params);
result.push(row);
}
catch (error) {
}
}
}
return result;
};
foreignKeyField.model['prototype'][uncapitalize(modelName) + '_set_all'] = async function () {
let _model = this;
let params = {};
let result = [];
params[`iD${_model.getModelName()}`] = _model.getPrimaryKeyValue();
const middleTableResult = await middleTable['filter'](params).execute();
let ids;
if (middleTableResult) {
const TableSchema = currentModel.getTableSchema();
ids = middleTableResult.map((e) => {
return e[`iD${modelName}`];
});
let params = {};
for (const id of ids) {
try {
params[TableSchema.id.keyPath] = id;
const row = await currentModel.get(params);
result.push(row);
}
catch (error) {
}
}
}
return result;
};
}
}
function generateGenericModel({ DBSchema, ModelName, TableSchema }) {
class GenericModel extends Model {
}
for (const [Field, value] of Object.entries(Model)) {
GenericModel[Field] = value;
}
// GenericModel.prototype = Model.prototype
GenericModel.prototype['getDBSchema'] = () => {
return DBSchema;
};
GenericModel.prototype['getModelName'] = () => {
return ModelName;
};
GenericModel.prototype['getTableSchema'] = () => {
return TableSchema;
};
GenericModel['getDBSchema'] = () => {
return DBSchema;
};
GenericModel['getModelName'] = () => {
return ModelName;
};
GenericModel['getTableSchema'] = () => {
return TableSchema;
};
return GenericModel;
}
@@ -1,10 +0,0 @@
import { TableSchema } from '../../models/register-modal.interface.js';
import { argsAttributes } from './args-attributes.js';
export declare class ObjectConditionOperator {
private TableSchema;
private args;
row: any;
constructor(TableSchema: TableSchema, args: argsAttributes);
run(row: any): boolean | any;
private execute;
}
@@ -1,33 +0,0 @@
export class ObjectConditionOperator {
constructor(TableSchema, args) {
this.TableSchema = TableSchema;
this.args = args;
}
run(row) {
this.row = row;
for (const arg of this.args.value) {
const result = this.execute(arg);
if (result) {
return true;
}
}
}
execute(objOperator) {
for (let objOperatorFieldName in objOperator) {
const field = objOperator[objOperatorFieldName];
const fieldName = field.fieldName;
const fieldPath = field.fieldPath;
const operation = field.operation;
const operationArg = field.operationArg;
const fieldClassName = field.fieldClassName;
const operator = field.operator;
const customData = field.customData({ row: this.row, fieldPath });
const arg = operationArg;
let operationResult = operator({ fieldName, arg, row: this.row, TableSchema: this.TableSchema, element: fieldName, fieldPath, customData });
if (!operationResult) {
return false;
}
}
return true;
}
}
-22
View File
@@ -1,22 +0,0 @@
import { AttributesMap, FieldKeys, FieldsMap } from "../../models/field/fields.interface.js";
import { OperatorKeys } from "./object-operator.js";
import { TableSchema, FieldSchema } from '../../models/register-modal.interface.js';
export interface Field {
fieldName: string;
fieldPath: string;
operation: OperatorKeys;
operationArg?: string;
operator: Function;
fieldClassName: FieldKeys;
customData?: Function;
}
export declare class argsAttributes {
private TableSchema;
value: Array<FieldsMap<string, Field>>;
schemeFields: AttributesMap<string, FieldSchema>;
constructor(args: any, TableSchema: TableSchema);
private analyzeArgs;
private detectClassName;
private detectOperator;
private argsPrettyTransform;
}
@@ -1,118 +0,0 @@
import { OperatorsKeysArray, operator, ObjOperatorOverwrite, ArrOperatorOverwrite } from "./object-operator.js";
import { info } from "./operators.js";
export class argsAttributes {
constructor(args, TableSchema) {
this.TableSchema = TableSchema;
this.value = [];
this.schemeFields = {} = {};
for (const field of this.TableSchema.fields) {
this.schemeFields[field.name] = field;
}
this.schemeFields[this.TableSchema.id.keyPath] = {
keyPath: this.TableSchema.id.keyPath,
name: this.TableSchema.id.keyPath,
className: 'IntegerField',
};
if (args.constructor.name != 'Array') {
args = [args];
}
const conditions = this.argsPrettyTransform(args);
this.value = this.analyzeArgs(conditions);
}
analyzeArgs(conditions) {
return conditions.map((condition) => {
const newObject = {};
const keys = Object.keys(condition);
for (let field of keys) {
let fieldName;
let fieldPath;
let arg;
const element = field.split('__');
if (element.length == 1) {
element.push('eq');
}
let operation = element[element.length - 1];
if (OperatorsKeysArray.includes(operation)) {
operation = element.pop();
}
else {
operation = 'eq';
}
fieldName = element[0];
fieldPath = element.join('.');
if (OperatorsKeysArray.includes(operation)) {
arg = condition[field];
}
else {
throw ('operator');
}
const fieldClassName = this.detectClassName(fieldName);
newObject[field] = {
fieldName: fieldName,
fieldPath: fieldPath,
operation: operation,
operationArg: arg,
operator: this.detectOperator(fieldClassName, operation, fieldName),
fieldClassName: fieldClassName,
};
if (fieldClassName == 'indexedDBArrayField' || fieldClassName == 'indexedDBJsonField') {
newObject[field]['customData'] = info.run;
}
else {
newObject[field]['customData'] = () => { };
}
}
return newObject;
});
}
detectClassName(fieldName) {
return this.schemeFields[fieldName].className;
}
detectOperator(fieldClassName, operation, fieldName) {
try {
if (fieldClassName == 'indexedDBJsonField') {
return ObjOperatorOverwrite[operation];
}
else if (fieldClassName == 'indexedDBArrayField') {
return ArrOperatorOverwrite[operation];
}
else {
return operator[operation];
}
}
catch (err) {
// console.log(this.TableSchema, this.schemeFields[fieldName])
throw ('Field ' + fieldName + ' does not exit on the table' + err);
}
}
argsPrettyTransform(args) {
const conditions = [];
const loop = (o) => {
// https://stackoverflow.com/a/38597076/14115342
const condition = {};
for (const k of Object.keys(o)) {
if (o[k].constructor.name === 'Array') {
loop(o[k]);
}
else {
if (o.constructor.name === 'Array') {
// console.log('dif', o, k , )
for (const j of Object.keys(o[k])) {
// console.log('push', o[k], j)
condition[j] = o[k][j];
}
}
else {
// console.log('push', o, k)
condition[k] = o[k];
}
}
}
if (JSON.stringify(condition) !== '{}') {
conditions.push(condition);
}
};
loop(args);
return conditions;
}
}
-478
View File
@@ -1,478 +0,0 @@
export declare const OperatorsKeysArray: readonly ["gt", "gte", "lt", "lte", "not", "eq", "contains", "len", "hasKey", "ForeignKey", "containedBy", "overlap", "isNull", "contained_by", "has_key", "has_keys", "has_any_keys", "len", "overlap", "iexact"];
export declare type OperatorKeys = typeof OperatorsKeysArray[number];
export declare const operator: {
gt: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
gte: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
lt: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
lte: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
not: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
eq: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
contains: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => any;
len({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
hasKey({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
containedBy({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
overlap({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): any;
isNull({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
iexact({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
};
export declare const ObjOperatorOverwrite: {
gt: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
gte: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
lt: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
lte: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
not: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
eq: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
contains: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => any;
len({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
hasKey({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
containedBy({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
overlap({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): any;
isNull({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
iexact({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
} & {
isNull({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
eq: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
contains: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
contained_by: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
has_key({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
has_keys({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
has_any_keys({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
};
export declare const ArrOperatorOverwrite: {
gt: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
gte: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
lt: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
lte: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
not: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
eq: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
contains: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => any;
len({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
hasKey({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
containedBy({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
overlap({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): any;
isNull({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
iexact({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
} & {
isNull({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}): boolean;
eq: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
contains: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
contained_by: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
len: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
overlap: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
TableSchema: any;
element: any;
fieldPath: any;
customData: any;
}) => boolean;
};
@@ -1,107 +0,0 @@
import * as operatorsObject from './operators.js';
export const OperatorsKeysArray = [
'gt',
'gte',
'lt',
'lte',
'not',
'eq',
'contains',
'len',
'hasKey',
'ForeignKey',
'containedBy',
'overlap',
'isNull',
'contained_by',
'has_key',
'has_keys',
'has_any_keys',
'len',
'overlap',
'iexact'
]; // TS3.4 syntax
export const operator = {
gt: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.gt.validate({ fieldName, arg, row, fieldPath, customData });
},
gte: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.gte.validate({ fieldName, arg, row, fieldPath, customData });
},
lt: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.lt.validate({ fieldName, arg, row, fieldPath, customData });
},
lte: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.lte.validate({ fieldName, arg, row, fieldPath });
},
not: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.not.validate({ fieldName, arg, row, fieldPath });
},
eq: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.eq.validate({ fieldName, arg, row, fieldPath, customData });
},
contains: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.contains.validate({ fieldName, arg, row, fieldPath, customData });
},
len({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.len.validate({ fieldName, arg, row, fieldPath, customData });
},
hasKey({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.hasKey.validate({ fieldName, arg, row, fieldPath, customData });
},
containedBy({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.containedBy.validate({ fieldName, arg, row, fieldPath, customData });
},
overlap({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.overlap.validate({ fieldName, arg, row, fieldPath, customData });
},
isNull({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.isNull.validate({ fieldName, arg, row, fieldPath, customData });
},
iexact({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.iexact.validate({ fieldName, arg, row, fieldPath, customData });
}
};
export const ObjOperatorOverwrite = Object.assign(Object.assign({}, operator), {
isNull({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.objectIsnull.validate({ fieldName, arg, row, fieldPath, customData });
},
eq: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.objectEq.validate({ fieldName, arg, row, fieldPath, customData });
},
contains: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.objectContains.validate({ fieldName, arg, row, fieldPath, customData });
},
contained_by: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.objectContains_by.validate({ fieldName, arg, row, fieldPath, customData });
},
has_key({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.objectHasKey.validate({ fieldName, arg, row, fieldPath, customData });
},
has_keys({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.objectHasKeys.validate({ fieldName, arg, row, fieldPath, customData });
},
has_any_keys({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.objectHasnyKeys.validate({ fieldName, arg, row, fieldPath, customData });
}
});
export const ArrOperatorOverwrite = Object.assign(Object.assign({}, operator), {
isNull({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) {
return operatorsObject.objectIsnull.validate({ fieldName, arg, row, fieldPath, customData });
},
eq: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.ArrayFieldEq.validate({ fieldName, arg, row, fieldPath, customData });
},
contains: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.ArrayFieldContains.validate({ fieldName, arg, row, fieldPath, customData });
},
contained_by: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.ArrayFieldContains_by.validate({ fieldName, arg, row, fieldPath, customData });
},
len: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.ArrayFieldContains_len.validate({ fieldName, arg, row, fieldPath, customData });
},
overlap: ({ fieldName, arg, row, TableSchema, element, fieldPath, customData }) => {
return operatorsObject.ArrayFieldContains_overlap.validate({ fieldName, arg, row, fieldPath, customData });
}
});
-258
View File
@@ -1,258 +0,0 @@
export declare class gt {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class iexact {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class gte {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class lt {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class lte {
static validate({ fieldName, arg, row, fieldPath }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
}): boolean;
}
export declare class not {
static validate({ fieldName, arg, row, fieldPath }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
}): boolean;
}
export declare class eq {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class contains {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): any;
}
export declare class info {
static run({ row, fieldPath }: {
row: any;
fieldPath: any;
}): {
value: any;
present: any;
};
}
export declare class containsOBj {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class containedBy {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class overlap {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): any;
}
export declare class len {
static validate({ fieldName, arg, rowFieldValue, row, fieldPath, customData }: {
fieldName: any;
arg: any;
rowFieldValue?: any[];
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class hasKey {
static validate({ fieldName, arg, rowFieldValue, row, fieldPath, customData }: {
fieldName: any;
arg: any;
rowFieldValue?: any[];
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class hasAnyKeys {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): any;
}
/**
* @returns true when all of the given keys are in the data
*/
export declare class hasKeys {
static validate(fieldObj: any, keys: any, row: any): boolean;
}
export declare class isNull {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class objectIsnull {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class objectEq {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class objectContains {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class objectContains_by {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class objectHasKey {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class objectHasKeys {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class objectHasnyKeys {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class ArrayFieldEq {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class ArrayFieldContains {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class ArrayFieldContains_by {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class ArrayFieldContains_overlap {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
export declare class ArrayFieldContains_len {
static validate({ fieldName, arg, row, fieldPath, customData }: {
fieldName: any;
arg: any;
row: any;
fieldPath: any;
customData: any;
}): boolean;
}
-576
View File
@@ -1,576 +0,0 @@
import { getDeep } from '../../utils.js';
export class gt {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue > arg;
}
}
export class iexact {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue === arg;
}
}
export class gte {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue >= arg;
}
}
export class lt {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue < arg;
}
}
export class lte {
static validate({ fieldName, arg, row, fieldPath }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue <= arg;
}
}
export class not {
static validate({ fieldName, arg, row, fieldPath }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue != arg;
}
}
export class eq {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue == arg;
}
}
export class contains {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue.some(r => arg.includes(r));
}
}
export class info {
static run({ row, fieldPath }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return {
present: false,
value: undefined
};
}
}
catch (error) {
return {
present: false,
value: undefined
};
}
return {
present: true,
value: undefined
};
}
}
export class containsOBj {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
const keys = Object.keys(arg);
for (let key of keys) {
if (!_rowFieldValue[key]) {
return false;
}
}
return true;
}
}
export class containedBy {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
for (let value of _rowFieldValue) {
if (!arg.includes(value)) {
return false;
}
}
return true;
}
}
export class overlap {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue.some(r => arg.includes(r));
}
}
export class len {
static validate({ fieldName, arg, rowFieldValue = [], row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue.length == arg;
}
}
export class hasKey {
static validate({ fieldName, arg, rowFieldValue = [], row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
const keys = Object.keys(arg);
for (let key of keys) {
if (!_rowFieldValue[key]) {
return false;
}
}
}
}
export class hasAnyKeys {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return _rowFieldValue.some(key => !arg.includes(key));
}
}
/**
* @returns true when all of the given keys are in the data
*/
export class hasKeys {
static validate(fieldObj, keys, row) {
for (let fieldName of keys) {
if (!fieldObj[fieldName]) {
return false;
}
}
return true;
}
}
// Slice transforms
export class isNull {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
return (_rowFieldValue == null) == arg;
}
}
// object
export class objectIsnull {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let rowFieldValue;
try {
rowFieldValue = getDeep(row, fieldPath);
if (rowFieldValue === undefined) {
if (arg == true) {
return true;
}
}
}
catch (error) {
if (arg == true) {
return true;
}
return false;
}
if (JSON.stringify(rowFieldValue) == '{}' && arg == false) {
return true;
}
else if (rowFieldValue == null && arg == true) {
return true;
}
else if (rowFieldValue == undefined) {
return true;
}
return false;
}
}
export class objectEq {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
if (JSON.stringify(_rowFieldValue = getDeep(row, fieldPath)) == '{}' && '{}' == JSON.stringify(arg)) {
return true;
}
else if (arg == null && JSON.stringify(_rowFieldValue) == '{}') {
return true;
}
else if (fieldPath) {
if (arg == _rowFieldValue) {
return true;
}
}
return false;
}
}
export class objectContains {
static validate({ fieldName, arg, row, fieldPath, customData }) {
// console.log(fieldName, arg, row)
let rowValue;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
for (const keys of Object.keys(arg)) {
if (!rowValue[keys]) {
return false;
}
else {
if (rowValue[keys] != arg[keys]) {
return false;
}
}
}
return true;
}
}
export class objectContains_by {
static validate({ fieldName, arg, row, fieldPath, customData }) {
// console.log(fieldName, arg, row);
let rowValue;
const keyCount = Object.keys(arg).length;
let keyFoundNEqual = 0;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
else {
for (const keys of Object.keys(arg)) {
if (rowValue[keys]) {
if (rowValue[keys] == arg[keys]) {
keyFoundNEqual++;
}
}
}
}
}
catch (error) {
return false;
}
// console.log('keyFoundNEqual', keyFoundNEqual, 'keyCount', keyCount);
if (keyFoundNEqual == 0) {
return true;
}
else if (keyFoundNEqual == keyCount) {
return true;
}
return false;
}
}
export class objectHasKey {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let rowValue;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
if (rowValue[arg]) {
return true;
}
return false;
}
}
export class objectHasKeys {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let rowValue;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
const keys = Object.keys(rowValue);
for (const a of arg) {
if (!keys.includes(a)) {
return false;
}
}
return true;
}
}
export class objectHasnyKeys {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let rowValue;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
const keys = Object.keys(rowValue);
for (const a of arg) {
if (keys.includes(a)) {
return true;
}
}
return false;
}
}
// array shit
export class ArrayFieldEq {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let _rowFieldValue;
try {
_rowFieldValue = getDeep(row, fieldPath);
if (_rowFieldValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
if (JSON.stringify(_rowFieldValue) == '[]' && '[]' == JSON.stringify(arg)) {
return true;
}
else if (arg == null && JSON.stringify(_rowFieldValue) == '[]') {
return true;
}
else if (fieldPath) {
if (arg == _rowFieldValue) {
return true;
}
}
return false;
}
}
export class ArrayFieldContains {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let rowValue;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
try {
for (const keys of arg) {
if (!rowValue.includes(keys)) {
return false;
}
}
}
catch (error) {
return false;
}
return true;
}
}
export class ArrayFieldContains_by {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let rowValue;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
try {
for (const keys of arg) {
if (rowValue.includes(keys)) {
return true;
}
}
}
catch (error) {
return false;
}
return false;
}
}
export class ArrayFieldContains_overlap {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let rowValue;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
try {
for (const keys of arg) {
if (rowValue.includes(keys)) {
return true;
}
}
}
catch (error) {
return false;
}
return false;
}
}
export class ArrayFieldContains_len {
static validate({ fieldName, arg, row, fieldPath, customData }) {
let rowValue;
try {
rowValue = getDeep(row, fieldPath);
if (rowValue === undefined) {
return false;
}
}
catch (error) {
return false;
}
if (rowValue.length == arg) {
return true;
}
return false;
}
}
View File
-11
View File
@@ -1,11 +0,0 @@
import { ObjectConditionOperator } from '../Operators/Object-condition-operator.js';
import { argsAttributes } from '../Operators/args-attributes.js';
export declare class filter {
private arg;
private TableSchema;
rows: any[];
operator: ObjectConditionOperator;
constructor(arg: argsAttributes, TableSchema: any);
cursor(row: object, resolve?: any, limit?: any): Promise<void>;
run(rows: any[]): Promise<any[]>;
}
-28
View File
@@ -1,28 +0,0 @@
import { ObjectConditionOperator } from '../Operators/Object-condition-operator.js';
export class filter {
constructor(arg, TableSchema) {
this.arg = arg;
this.TableSchema = TableSchema;
this.rows = [];
this.operator = new ObjectConditionOperator(this.TableSchema, this.arg);
}
async cursor(row, resolve, limit) {
const operationsResult = await this.operator.run(row);
if (operationsResult == true) {
this.rows.push(row);
if (this.rows.length == limit) {
resolve(this.rows);
}
}
}
async run(rows) {
const newRows = [];
for (let row of rows) {
const operationsResult = await this.operator.run(row);
if (operationsResult == true) {
newRows.push(row);
}
}
return newRows;
}
}
-14
View File
@@ -1,14 +0,0 @@
export declare const methodsType: readonly ["filter"];
export declare type methodsTypeKeys = typeof methodsType[number];
export declare type methodsMap<K extends string | number | symbol, T> = {
[P in K]?: T;
};
export declare class methodFunction {
private arg;
private TableSchema;
rows: any[];
constructor(arg: any, TableSchema: any);
cursor(row: object, resolve?: any, limit?: any): Promise<void>;
run(rows: any[]): Promise<any[]>;
}
export declare const methods: methodsMap<methodsTypeKeys, methodFunction>;
-7
View File
@@ -1,7 +0,0 @@
import { filter } from './filter.js';
export const methodsType = [
'filter',
]; // TS3.4 syntax
export const methods = {
filter: filter
};
-12
View File
@@ -1,12 +0,0 @@
export declare enum FieldType {
AUTO = 0,
INT = 1,
BIGINT = 2,
TEXT = 3,
VARCHAR = 4,
DATE = 5,
BOOL = 6,
CHAR = 7,
JSON = 8,
ARRAY = 9
}
-14
View File
@@ -1,14 +0,0 @@
export var FieldType;
(function (FieldType) {
FieldType[FieldType["AUTO"] = 0] = "AUTO";
FieldType[FieldType["INT"] = 1] = "INT";
FieldType[FieldType["BIGINT"] = 2] = "BIGINT";
FieldType[FieldType["TEXT"] = 3] = "TEXT";
FieldType[FieldType["VARCHAR"] = 4] = "VARCHAR";
FieldType[FieldType["DATE"] = 5] = "DATE";
FieldType[FieldType["BOOL"] = 6] = "BOOL";
FieldType[FieldType["CHAR"] = 7] = "CHAR";
FieldType[FieldType["JSON"] = 8] = "JSON";
FieldType[FieldType["ARRAY"] = 9] = "ARRAY";
})(FieldType || (FieldType = {}));
//
-3
View File
@@ -1,3 +0,0 @@
declare class sql {
filter(): void;
}
-3
View File
@@ -1,3 +0,0 @@
class sql {
filter() { }
}
-17
View File
@@ -1,17 +0,0 @@
import { Method } from '../../models/model.interface.js';
import { TableSchema } from '../../models/register-modal.interface.js';
import { methodFunction } from '../methods/methods.js';
import { argsAttributes } from '../Operators/args-attributes.js';
export declare class SqlObject {
private TableSchema;
private Methods;
limit: number;
rows: any[];
firstMethod: methodFunction;
params: any[];
argsAttributes: argsAttributes;
constructor(TableSchema: TableSchema, Methods: Method[]);
runFirstMethod(row: any, resolve?: any, limit?: any): Promise<void>;
doneRunFirstMethod(): Promise<void>;
run(): Promise<void>;
}
-31
View File
@@ -1,31 +0,0 @@
import { methods } from '../methods/methods.js';
import { argsAttributes } from '../Operators/args-attributes.js';
export class SqlObject {
constructor(TableSchema, Methods) {
this.TableSchema = TableSchema;
this.Methods = Methods;
this.limit = 0;
this.rows = [];
this.params = [];
const arg = this.Methods[0].arguments;
const methodName = this.Methods[0].methodName;
this.argsAttributes = new argsAttributes(arg, TableSchema);
this.firstMethod = new methods[methodName](this.argsAttributes, this.TableSchema);
}
async runFirstMethod(row, resolve, limit) {
this.firstMethod.cursor(row, resolve, limit);
}
async doneRunFirstMethod() {
this.rows = this.firstMethod.rows;
}
async run() {
for (let i = 1; i < this.Methods.length; i++) {
const method = this.Methods[i];
const methodName = method.methodName;
if (methods[methodName]) {
const methodToExecute = new methods[methodName](this.argsAttributes, this.TableSchema);
this.rows = await methodToExecute.run(this.rows);
}
}
}
}
-7
View File
@@ -1,7 +0,0 @@
export declare function uniqueGenerator(): string;
export declare function hashCode(str: string): number;
export declare function getDeep(obj: any, path: any): any;
/** First Character uppercase */
export declare function capitalize(str: any): any;
/** First Character lowercase */
export declare function uncapitalize(str: any): any;
-34
View File
@@ -1,34 +0,0 @@
// generate unique string
export function uniqueGenerator() {
return (Math.random() + 'uuid' + new Date().getTime()).slice(2);
}
export function hashCode(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
var char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash;
}
export function getDeep(obj, path) {
try {
for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) {
obj = obj[path[i]];
}
;
return obj;
}
catch (error) {
return undefined;
}
}
;
/** First Character uppercase */
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/** First Character lowercase */
export function uncapitalize(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}