refactor: ipc handlers ts refactor

This commit is contained in:
Fabio Di Stasio 2022-04-15 14:56:13 +02:00
parent 25a6fded2e
commit a315eeae6c
20 changed files with 219 additions and 75 deletions

View File

@ -105,6 +105,7 @@
},
"dependencies": {
"@electron/remote": "^2.0.1",
"@faker-js/faker": "^6.1.2",
"@mdi/font": "^6.1.95",
"@turf/helpers": "^6.5.0",
"@vscode/vscode-languagedetection": "^1.0.21",

View File

@ -134,7 +134,7 @@ export default class {
{ name: 'phoneNumberFormat', group: 'phone', types: ['string'] },
{ name: 'phoneFormats', group: 'phone', types: ['string'] },
{ name: 'number', group: 'datatype', types: ['string', 'number'], params: ['min', 'max'] },
{ name: 'number', group: 'random', types: ['string', 'number'], params: ['min', 'max'] },
{ name: 'float', group: 'random', types: ['string', 'float'], params: ['min', 'max'] },
{ name: 'arrayElement', group: 'random', types: ['string'] },
{ name: 'arrayElements', group: 'random', types: ['string'] },
@ -195,7 +195,7 @@ export default class {
return 1;
return 0;
}); ;
});
}
static getGroupsByType (type) {

View File

@ -251,11 +251,12 @@ export interface QueryBuilderObject {
where: string[];
groupBy: string[];
orderBy: string[];
limit: string[];
offset: string[];
limit: number;
offset: number;
join: string[];
update: string[];
insert: string[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
insert: {[key: string]: any}[];
delete: boolean;
}

View File

@ -0,0 +1,20 @@
import { UsableLocale } from '@faker-js/faker';
export interface InsertRowsParams {
uid: string;
schema: string;
table: string;
row: {[key: string]: {
group: string;
method: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any;
length: number;
};
};
repeat: number;
fields: {[key: string]: string};
locale: UsableLocale;
}

View File

@ -0,0 +1,7 @@
export type WorkerEvent = 'export-progress' | 'import-progress' | 'query-error' | 'end' | 'cancel' | 'error'
export interface WorkerIpcMessage {
type: WorkerEvent;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: any;
}

View File

@ -1,6 +1,7 @@
import * as antares from 'common/interfaces/antares';
import { ipcMain } from 'electron';
export default (connections) => {
export default (connections: {[key: string]: antares.Client}) => {
ipcMain.handle('get-function-informations', async (event, params) => {
try {
const result = await connections[params.uid].getFunctionInformations(params);

View File

@ -1,6 +1,7 @@
import * as antares from 'common/interfaces/antares';
import { ipcMain } from 'electron';
export default (connections) => {
export default (connections: {[key: string]: antares.Client}) => {
ipcMain.handle('get-routine-informations', async (event, params) => {
try {
const result = await connections[params.uid].getRoutineInformations(params);

View File

@ -1,6 +1,7 @@
import * as antares from 'common/interfaces/antares';
import { ipcMain } from 'electron';
export default (connections) => {
export default (connections: {[key: string]: antares.Client}) => {
ipcMain.handle('get-scheduler-informations', async (event, params) => {
try {
const result = await connections[params.uid].getEventInformations(params);

View File

@ -1,14 +1,15 @@
import * as antares from 'common/interfaces/antares';
import * as workers from 'common/interfaces/workers';
import fs from 'fs';
import path from 'path';
import { fork } from 'child_process';
import { ChildProcess, fork } from 'child_process';
import { ipcMain, dialog } from 'electron';
// @TODO: need some factories
const isDevelopment = process.env.NODE_ENV !== 'production';
export default connections => {
let exporter = null;
let importer = null;
export default (connections: {[key: string]: antares.Client}) => {
let exporter: ChildProcess = null;
let importer: ChildProcess = null;
ipcMain.handle('create-schema', async (event, params) => {
try {
@ -51,9 +52,7 @@ export default connections => {
return {
status: 'success',
response: collation.rows.length
? collation.rows[0].DEFAULT_COLLATION_NAME
: ''
response: collation
};
}
catch (err) {
@ -175,7 +174,7 @@ export default connections => {
ipcMain.handle('export', (event, { uid, type, tables, ...rest }) => {
if (exporter !== null) return;
return new Promise((resolve, reject) => {
return new Promise((resolve/*, reject */) => {
(async () => {
if (fs.existsSync(rest.outputFile)) { // If file exists ask for replace
const result = await dialog.showMessageBox({
@ -211,7 +210,7 @@ export default connections => {
});
// Exporter message listener
exporter.on('message', ({ type, payload }) => {
exporter.on('message', ({ type, payload }: workers.WorkerIpcMessage) => {
switch (type) {
case 'export-progress':
event.sender.send('export-progress', payload);
@ -244,7 +243,7 @@ export default connections => {
});
});
ipcMain.handle('abort-export', async event => {
ipcMain.handle('abort-export', async () => {
let willAbort = false;
if (exporter) {
@ -268,7 +267,7 @@ export default connections => {
ipcMain.handle('import-sql', async (event, options) => {
if (importer !== null) return;
return new Promise((resolve, reject) => {
return new Promise((resolve/*, reject */) => {
(async () => {
const dbConfig = await connections[options.uid].getDbConfig();
@ -283,7 +282,7 @@ export default connections => {
});
// Importer message listener
importer.on('message', ({ type, payload }) => {
importer.on('message', ({ type, payload }: workers.WorkerIpcMessage) => {
switch (type) {
case 'import-progress':
event.sender.send('import-progress', payload);
@ -314,7 +313,7 @@ export default connections => {
});
});
ipcMain.handle('abort-import-sql', async event => {
ipcMain.handle('abort-import-sql', async () => {
let willAbort = false;
if (importer) {

View File

@ -1,12 +1,14 @@
import * as antares from 'common/interfaces/antares';
import { InsertRowsParams } from 'common/interfaces/tableApis';
import { ipcMain } from 'electron';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import moment from 'moment';
import { sqlEscaper } from 'common/libs/sqlEscaper';
import { TEXT, LONG_TEXT, ARRAY, TEXT_SEARCH, NUMBER, FLOAT, BLOB, BIT, DATE, DATETIME } from 'common/fieldTypes';
import * as customizations from 'common/customizations';
import fs from 'fs';
export default (connections) => {
export default (connections: {[key: string]: antares.Client}) => {
ipcMain.handle('get-table-columns', async (event, params) => {
try {
const result = await connections[params.uid].getTableColumns(params);
@ -196,7 +198,8 @@ export default (connections) => {
ipcMain.handle('delete-table-rows', async (event, params) => {
if (params.primary) {
const idString = params.rows.map(row => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const idString = params.rows.map((row: {[key: string]: any}) => {
const fieldName = Object.keys(row)[0].includes('.') ? `${params.table}.${params.primary}` : params.primary;
return typeof row[fieldName] === 'string'
@ -245,7 +248,8 @@ export default (connections) => {
ipcMain.handle('insert-table-rows', async (event, params) => {
try { // TODO: move to client classes
const insertObj = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const insertObj: {[key: string]: any} = {};
for (const key in params.row) {
const type = params.fields[key];
let escapedParam;
@ -312,12 +316,14 @@ export default (connections) => {
}
});
ipcMain.handle('insert-table-fake-rows', async (event, params) => {
ipcMain.handle('insert-table-fake-rows', async (event, params: InsertRowsParams) => {
try { // TODO: move to client classes
const rows = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows: {[key: string]: any}[] = [];
for (let i = 0; i < +params.repeat; i++) {
const insertObj = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const insertObj: {[key: string]: any} = {};
for (const key in params.row) {
const type = params.fields[key];
@ -375,7 +381,8 @@ export default (connections) => {
insertObj[key] = escapedParam;
}
else { // Faker value
const parsedParams = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const parsedParams: {[key: string]: any} = {};
let fakeValue;
if (params.locale)
@ -386,10 +393,12 @@ export default (connections) => {
if (!isNaN(params.row[key].params[param]))
parsedParams[param] = +params.row[key].params[param];
});
fakeValue = faker[params.row[key].group][params.row[key].method](parsedParams);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fakeValue = (faker as any)[params.row[key].group][params.row[key].method](parsedParams);
}
else
fakeValue = faker[params.row[key].group][params.row[key].method]();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fakeValue = (faker as any)[params.row[key].group][params.row[key].method]();
if (typeof fakeValue === 'string') {
if (params.row[key].length)

View File

@ -1,6 +1,7 @@
import * as antares from 'common/interfaces/antares';
import { ipcMain } from 'electron';
export default (connections) => {
export default (connections: {[key: string]: antares.Client}) => {
ipcMain.handle('get-trigger-informations', async (event, params) => {
try {
const result = await connections[params.uid].getTriggerInformations(params);

View File

@ -4,8 +4,8 @@ import Store from 'electron-store';
const persistentStore = new Store({ name: 'settings' });
const isMacOS = process.platform === 'darwin';
let mainWindow;
autoUpdater.allowPrerelease = persistentStore.get('allow_prerelease', true);
let mainWindow: Electron.IpcMainEvent;
autoUpdater.allowPrerelease = persistentStore.get('allow_prerelease', true) as boolean;
export default () => {
ipcMain.on('check-for-updates', event => {
@ -50,7 +50,7 @@ export default () => {
mainWindow.reply('update-downloaded');
});
autoUpdater.logger = require('electron-log');
autoUpdater.logger.transports.console.format = '{h}:{i}:{s} {text}';
autoUpdater.logger.transports.file.level = 'info';
// autoUpdater.logger = require('electron-log');
// autoUpdater.logger.transports.console.format = '{h}:{i}:{s} {text}';
// autoUpdater.logger.transports.file.level = 'info';
};

View File

@ -1,6 +1,7 @@
import * as antares from 'common/interfaces/antares';
import { ipcMain } from 'electron';
export default (connections) => {
export default (connections: {[key: string]: antares.Client}) => {
ipcMain.handle('get-users', async (event, uid) => {
try {
const result = await connections[uid].getUsers();

View File

@ -1,6 +1,7 @@
import * as antares from 'common/interfaces/antares';
import { ipcMain } from 'electron';
export default (connections) => {
export default (connections: {[key: string]: antares.Client}) => {
ipcMain.handle('get-view-informations', async (event, params) => {
try {
const result = await connections[params.uid].getViewInformations(params);

View File

@ -13,7 +13,7 @@ const queryLogger = (sql: string) => {
* As Simple As Possible Query Builder Core
*/
export class AntaresCore {
protected _client: string;
_client: antares.ClientCode;
protected _params: mysql.ConnectionOptions | pg.ClientConfig | { databasePath: string; readonly: boolean};
protected _poolSize: number;
protected _ssh?: SSH2Promise;
@ -34,8 +34,8 @@ export class AntaresCore {
where: [],
groupBy: [],
orderBy: [],
limit: [],
offset: [],
limit: null,
offset: null,
join: [],
update: [],
insert: [],
@ -113,13 +113,13 @@ export class AntaresCore {
return this;
}
limit (...args: string[]) {
this._query.limit = args;
limit (limit: number) {
this._query.limit = limit;
return this;
}
offset (...args: string[]) {
this._query.offset = args;
offset (offset: number) {
this._query.offset = offset;
return this;
}
@ -129,7 +129,8 @@ export class AntaresCore {
return this;
}
insert (arr: string[]) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
insert (arr: {[key: string]: any}[]) {
this._query.insert = [...this._query.insert, ...arr];
return this;
}
@ -148,4 +149,112 @@ export class AntaresCore {
this._resetQuery();
return this.raw<antares.QueryResult<RowType>>(rawQuery, args);
}
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
getDbConfig () {
throw new Error('Method "getDbConfig" not implemented');
}
createSchema (...args: any) {
throw new Error('Method "createSchema" not implemented');
}
alterSchema (...args: any) {
throw new Error('Method "alterSchema" not implemented');
}
dropSchema (...args: any) {
throw new Error('Method "dropSchema" not implemented');
}
getDatabaseCollation (...args: any) {
throw new Error('Method "getDatabaseCollation" not implemented');
}
getFunctionInformations (...args: any) {
throw new Error('Method "getFunctionInformations" not implemented');
}
alterFunction (...args: any) {
throw new Error('Method "alterFunction" not implemented');
}
createTriggerFunction (...args: any) {
throw new Error('Method "createTriggerFunction" not implemented');
}
alterTriggerFunction (...args: any) {
throw new Error('Method "alterTriggerFunction" not implemented');
}
createFunction (...args: any) {
throw new Error('Method "createFunction" not implemented');
}
dropFunction (...args: any) {
throw new Error('Method "dropFunction" not implemented');
}
getCollations () {
throw new Error('Method "getCollations" not implemented');
}
getRoutineInformations (...args: any) {
throw new Error('Method "getRoutineInformations" not implemented');
}
dropRoutine (...args: any) {
throw new Error('Method "dropRoutine" not implemented');
}
alterRoutine (...args: any) {
throw new Error('Method "alterRoutine" not implemented');
}
createRoutine (...args: any) {
throw new Error('Method "createRoutine" not implemented');
}
getVariables () {
throw new Error('Method "getVariables" not implemented');
}
getEventInformations (...args: any) {
throw new Error('Method "getEventInformations" not implemented');
}
dropEvent (...args: any) {
throw new Error('Method "dropEvent" not implemented');
}
alterEvent (...args: any) {
throw new Error('Method "alterEvent" not implemented');
}
createEvent (...args: any) {
throw new Error('Method "createEvent" not implemented');
}
enableEvent (...args: any) {
throw new Error('Method "enableEvent" not implemented');
}
disableEvent (...args: any) {
throw new Error('Method "disableEvent" not implemented');
}
enableTrigger (...args: any) {
throw new Error('Method "enableTrigger" not implemented');
}
disableTrigger (...args: any) {
throw new Error('Method "disableTrigger" not implemented');
}
killTabQuery (...args: any) {
throw new Error('Method "killTabQuery" not implemented');
}
/* eslint-enable @typescript-eslint/no-unused-vars */
/* eslint-enable @typescript-eslint/no-explicit-any */
}

View File

@ -720,7 +720,13 @@ export class MySQLClient extends AntaresCore {
}
async getDatabaseCollation (params: { database: string }) {
return await this.raw(`SELECT \`DEFAULT_COLLATION_NAME\` FROM \`information_schema\`.\`SCHEMATA\` WHERE \`SCHEMA_NAME\`='${params.database}'`);
let collation: string;
const { rows: collaitons } = await this.raw<antares.QueryResult<{DEFAULT_COLLATION_NAME: string}>>(`SELECT \`DEFAULT_COLLATION_NAME\` FROM \`information_schema\`.\`SCHEMATA\` WHERE \`SCHEMA_NAME\`='${params.database}'`);
if (collaitons.length)
collation = collaitons[0].DEFAULT_COLLATION_NAME;
return collation;
}
async createTable (params: antares.CreateTableParams) {
@ -1496,10 +1502,10 @@ export class MySQLClient extends AntaresCore {
const orderByRaw = orderByArray.length ? `ORDER BY ${orderByArray.join(', ')} ` : '';
// LIMIT
const limitRaw = this._query.limit.length ? `LIMIT ${this._query.limit.join(', ')} ` : '';
const limitRaw = this._query.limit ? `LIMIT ${this._query.limit} ` : '';
// OFFSET
const offsetRaw = this._query.offset.length ? `OFFSET ${this._query.offset.join(', ')} ` : '';
const offsetRaw = this._query.offset ? `OFFSET ${this._query.offset} ` : '';
return `${selectRaw}${updateRaw ? 'UPDATE' : ''}${insertRaw ? 'INSERT ' : ''}${this._query.delete ? 'DELETE ' : ''}${fromRaw}${updateRaw}${whereRaw}${groupByRaw}${orderByRaw}${limitRaw}${offsetRaw}${insertRaw}`;
}

View File

@ -82,11 +82,6 @@ export class PostgreSQLClient extends AntaresCore {
return type.replace('_', '');
}
/**
*
* @returns dbConfig
* @memberof PostgreSQLClient
*/
async getDbConfig () {
this._params.application_name = 'Antares SQL';
@ -1164,10 +1159,6 @@ export class PostgreSQLClient extends AntaresCore {
return await this.raw(sql, { split: false });
}
async getCollations (): Promise<null[]> {
return [];
}
async getVariables () {
interface ShowVariablesResult {
name: string;
@ -1305,10 +1296,10 @@ export class PostgreSQLClient extends AntaresCore {
const orderByRaw = orderByArray.length ? `ORDER BY ${orderByArray.join(', ')} ` : '';
// LIMIT
const limitRaw = selectArray.length && this._query.limit.length ? `LIMIT ${this._query.limit.join(', ')} ` : '';
const limitRaw = selectArray.length && this._query.limit ? `LIMIT ${this._query.limit} ` : '';
// OFFSET
const offsetRaw = selectArray.length && this._query.offset.length ? `OFFSET ${this._query.offset.join(', ')} ` : '';
const offsetRaw = selectArray.length && this._query.offset ? `OFFSET ${this._query.offset} ` : '';
return `${selectRaw}${updateRaw ? 'UPDATE' : ''}${insertRaw ? 'INSERT ' : ''}${this._query.delete ? 'DELETE ' : ''}${fromRaw}${updateRaw}${whereRaw}${groupByRaw}${orderByRaw}${limitRaw}${offsetRaw}${insertRaw}`;
}

View File

@ -476,14 +476,6 @@ export class SQLiteClient extends AntaresCore {
return await this.raw(sql, { split: false });
}
async getCollations (): Promise<undefined[]> {
return [];
}
async getVariables (): Promise<undefined[]> {
return [];
}
async getEngines () {
return {
name: 'SQLite',
@ -585,10 +577,10 @@ export class SQLiteClient extends AntaresCore {
const orderByRaw = orderByArray.length ? `ORDER BY ${orderByArray.join(', ')} ` : '';
// LIMIT
const limitRaw = this._query.limit.length ? `LIMIT ${this._query.limit.join(', ')} ` : '';
const limitRaw = this._query.limit ? `LIMIT ${this._query.limit} ` : '';
// OFFSET
const offsetRaw = this._query.offset.length ? `OFFSET ${this._query.offset.join(', ')} ` : '';
const offsetRaw = this._query.offset ? `OFFSET ${this._query.offset} ` : '';
return `${selectRaw}${updateRaw ? 'UPDATE' : ''}${insertRaw ? 'INSERT ' : ''}${this._query.delete ? 'DELETE ' : ''}${fromRaw}${updateRaw}${whereRaw}${groupByRaw}${orderByRaw}${limitRaw}${offsetRaw}${insertRaw}`;
}

View File

@ -151,17 +151,20 @@ Generation time: ${moment().format()}
return this.buildComment(`Dump completed on ${moment().format()}`);
}
getCreateTable (tableName) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getCreateTable (_tableName) {
throw new Error(
'Sql Exporter must implement the "getCreateTable" method'
);
}
getDropTable (tableName) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getDropTable (_tableName) {
throw new Error('Sql Exporter must implement the "getDropTable" method');
}
getTableInsert (tableName) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getTableInsert (_tableName) {
throw new Error(
'Sql Exporter must implement the "getTableInsert" method'
);