Skip to content

Commit 14af06c

Browse files
authored
Merge pull request #445 from devforth/feature/AdminForth/1137/lets-remove-heavy_debug-and-in
Feature/admin forth/1137/lets remove heavy debug and in
2 parents 16502b0 + f35d1c6 commit 14af06c

File tree

30 files changed

+670
-251
lines changed

30 files changed

+670
-251
lines changed

adminforth/auth.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import jwt from 'jsonwebtoken';
33
import crypto from 'crypto';
44
import AdminForth from './index.js';
55
import { IAdminForthAuth } from './types/Back.js';
6+
import { afLogger } from './modules/logger.js';
67

78
// Function to generate a password hash using PBKDF2
89
function calcPasswordHash(password, salt, iterations = 100000, keyLength = 64, digest = 'sha512') {
@@ -105,7 +106,7 @@ class AdminForthAuth implements IAdminForthAuth {
105106
if (expirySeconds !== undefined) {
106107
expiryMs = expirySeconds * 1000;
107108
} else if (expiry !== undefined) {
108-
console.warn('setCustomCookie: expiry(in ms) is deprecated, use expirySeconds instead (seconds), traceback:', new Error().stack);
109+
afLogger.warn(`setCustomCookie: expiry(in ms) is deprecated, use expirySeconds instead (seconds), traceback: ${new Error().stack}`);
109110
expiryMs = expiry;
110111
}
111112

@@ -145,23 +146,23 @@ class AdminForthAuth implements IAdminForthAuth {
145146
decoded = jwt.verify(jwtToken, secret);
146147
} catch (err) {
147148
if (err.name === 'TokenExpiredError') {
148-
console.error('Token expired:', err.message);
149+
afLogger.error(`Token expired: ${err.message}`);
149150
} else if (err.name === 'JsonWebTokenError') {
150-
console.error('Token error:', err.message);
151+
afLogger.error(`Token error: ${err.message}`);
151152
} else {
152-
console.error('Failed to verify JWT token', err);
153+
afLogger.error(`Failed to verify JWT token: ${err}`);
153154
}
154155
return null;
155156
}
156157
const { pk, t } = decoded;
157158
if (t !== mustHaveType) {
158-
console.error(`Invalid token type during verification: ${t}, must be ${mustHaveType}`);
159+
afLogger.error(`Invalid token type during verification: ${t}, must be ${mustHaveType}`);
159160
return null;
160161
}
161162
if (decodeUser !== false) {
162163
const dbUser = await this.adminforth.getUserByPk(pk);
163164
if (!dbUser) {
164-
console.error(`User with pk ${pk} not found in database`);
165+
afLogger.error(`User with pk ${pk} not found in database`);
165166
// will logout user which was deleted
166167
return null;
167168
}

adminforth/basePlugin.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import fs from 'fs';
66

77
import crypto from 'crypto';
88

9+
import { afLogger } from './modules/logger.js';
10+
911

1012
export default class AdminForthPlugin implements IAdminForthPlugin {
1113

@@ -24,7 +26,7 @@ export default class AdminForthPlugin implements IAdminForthPlugin {
2426
this.pluginDir = currentFileDir(metaUrl);
2527
this.customFolderPath = path.join(this.pluginDir, this.customFolderName);
2628
this.pluginOptions = pluginOptions;
27-
process.env.HEAVY_DEBUG && console.log(`🪲 🪲 AdminForthPlugin.constructor`, this.constructor.name);
29+
afLogger.trace(`🪲 🪲 AdminForthPlugin.constructor ${this.constructor.name}`);
2830
this.className = this.constructor.name;
2931
}
3032

@@ -46,7 +48,7 @@ export default class AdminForthPlugin implements IAdminForthPlugin {
4648

4749
const seed = `af_pl_${this.constructor.name}_${resourceConfig.resourceId}_${uniqueness}`;
4850
this.pluginInstanceId = md5hash(seed);
49-
process.env.HEAVY_DEBUG && console.log(`🪲 AdminForthPlugin.modifyResourceConfig`, seed, 'id', this.pluginInstanceId);
51+
afLogger.trace(`🪲 AdminForthPlugin.modifyResourceConfig, ${seed}, 'id', ${this.pluginInstanceId}`);
5052
this.adminforth = adminforth;
5153
}
5254

adminforth/commands/createApp/templates/adminuser.ts.hbs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import AdminForth, { AdminForthDataTypes } from 'adminforth';
22
import type { AdminForthResourceInput, AdminForthResource, AdminUser } from 'adminforth';
33
import { randomUUID } from 'crypto';
4+
import { logger } from 'adminforth';
45

56
async function allowedForSuperAdmin({ adminUser }: { adminUser: AdminUser }): Promise<boolean> {
67
return adminUser.dbUser.role === 'superadmin';
@@ -94,7 +95,7 @@ export default {
9495
},
9596
edit: {
9697
beforeSave: async ({ oldRecord, updates, adminUser, resource }: { oldRecord: any, updates: any, adminUser: AdminUser, resource: AdminForthResource }) => {
97-
console.log('Updating user', updates);
98+
logger.info(`Updating user, ${updates}`);
9899
if (oldRecord.id === adminUser.dbUser.id && updates.role) {
99100
return { ok: false, error: 'You cannot change your own role' };
100101
}

adminforth/commands/createApp/templates/index.ts.hbs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'url';
55
import path from 'path';
66
import { Filters } from 'adminforth';
77
import { initApi } from './api.js';
8+
import { logger } from 'adminforth';
89

910
const ADMIN_BASE_URL = '';
1011

@@ -75,7 +76,7 @@ if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
7576
const port = 3500;
7677

7778
admin.bundleNow({ hotReload: process.env.NODE_ENV === 'development' }).then(() => {
78-
console.log('Bundling AdminForth SPA done.');
79+
logger.info('Bundling AdminForth SPA done.');
7980
});
8081

8182
admin.express.serve(app);
@@ -91,6 +92,6 @@ if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
9192
});
9293

9394
admin.express.listen(port, () => {
94-
console.log(`\n⚡ AdminForth is available at http://localhost:${port}${ADMIN_BASE_URL}\n`);
95+
logger.info(`\n⚡ AdminForth is available at http://localhost:${port}${ADMIN_BASE_URL}\n`);
9596
});
9697
}

adminforth/dataConnectors/baseConnector.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@ import { suggestIfTypo } from "../modules/utils.js";
1010
import { AdminForthDataTypes, AdminForthFilterOperators, AdminForthSortDirections } from "../types/Common.js";
1111
import { randomUUID } from "crypto";
1212
import dayjs from "dayjs";
13+
import { afLogger } from '../modules/logger.js';
1314

1415

1516
export default class AdminForthBaseConnector implements IAdminForthDataSourceConnectorBase {
1617

1718
client: any;
1819

1920
get db() {
20-
console.warn('.db is deprecated, use .client instead');
21+
afLogger.warn('.db is deprecated, use .client instead');
2122
return this.client;
2223
}
2324

@@ -80,7 +81,6 @@ export default class AdminForthBaseConnector implements IAdminForthDataSourceCon
8081
// in case column isArray and enumerator/foreign resource - IN filter must be transformed into OR filter
8182
if (filterValidation.ok && f.operator == AdminForthFilterOperators.IN) {
8283
const column = resource.dataSourceColumns.find((col) => col.name == (f as IAdminForthSingleFilter).field);
83-
// console.log(`\n~~~ column: ${JSON.stringify(column, null, 2)}\n~~~ resource.columns: ${JSON.stringify(resource.dataSourceColumns, null, 2)}\n~~~ filter: ${JSON.stringify(f, null, 2)}\n`);
8484
if (column.isArray?.enabled && (column.enum || column.foreignResource)) {
8585
filters[fIndex] = {
8686
operator: AdminForthFilterOperators.OR,
@@ -138,7 +138,7 @@ export default class AdminForthBaseConnector implements IAdminForthDataSourceCon
138138
);
139139
}
140140
if (isPolymorphicTarget) {
141-
process.env.HEAVY_DEBUG && console.log(`⚠️ Field '${filtersAsSingle.field}' not found in polymorphic target resource '${resource.resourceId}', allowing query to proceed.`);
141+
afLogger.trace(`⚠️ Field '${filtersAsSingle.field}' not found in polymorphic target resource '${resource.resourceId}', allowing query to proceed.`);
142142
return { ok: true, error: '' };
143143
} else {
144144
throw new Error(`Field '${filtersAsSingle.field}' not found in resource '${resource.resourceId}'. ${similar ? `Did you mean '${similar}'?` : ''}`);
@@ -329,7 +329,7 @@ export default class AdminForthBaseConnector implements IAdminForthDataSourceCon
329329
}
330330

331331
async checkUnique(resource: AdminForthResource, column: AdminForthResourceColumn, value: any, record?: any): Promise<boolean> {
332-
process.env.HEAVY_DEBUG && console.log('☝️🪲🪲🪲🪲 checkUnique|||', column, value);
332+
afLogger.trace(`☝️🪲🪲🪲🪲 checkUnique||| ${column.name}, ${value}`);
333333

334334
const primaryKeyField = this.getPrimaryKey(resource);
335335
const existingRecord = await this.getData({
@@ -385,11 +385,11 @@ export default class AdminForthBaseConnector implements IAdminForthDataSourceCon
385385
})
386386
);
387387
if (error) {
388-
process.env.HEAVY_DEBUG && console.log('🪲🆕 check unique error', error);
388+
afLogger.trace(`🪲🆕 check unique error, ${error}`);
389389
return { error, ok: false };
390390
}
391391

392-
process.env.HEAVY_DEBUG && console.log('🪲🆕 creating record',JSON.stringify(recordWithOriginalValues));
392+
afLogger.trace(`🪲🆕 creating record, ${JSON.stringify(recordWithOriginalValues)}`);
393393
let pkValue = await this.createRecordOriginalValues({ resource, record: recordWithOriginalValues });
394394
if (recordWithOriginalValues[this.getPrimaryKey(resource)] !== undefined) {
395395
// some data sources always return some value for pk, even if it is was not auto generated
@@ -441,12 +441,12 @@ export default class AdminForthBaseConnector implements IAdminForthDataSourceCon
441441
})
442442
);
443443
if (error) {
444-
process.env.HEAVY_DEBUG && console.log('🪲🆕 check unique error', error);
444+
afLogger.trace(`🪲🆕 check unique error, ${error}`);
445445
return { error, ok: false };
446446
}
447447

448448

449-
process.env.HEAVY_DEBUG && console.log(`🪲✏️ updating record id:${recordId}, values: ${JSON.stringify(recordWithOriginalValues)}`);
449+
afLogger.trace(`🪲✏️ updating record id:${recordId}, values: ${JSON.stringify(recordWithOriginalValues)}`);
450450

451451
await this.updateRecordOriginalValues({ resource, recordId, newValues: recordWithOriginalValues });
452452

adminforth/dataConnectors/clickhouse.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import dayjs from 'dayjs';
44
import { createClient } from '@clickhouse/client'
55

66
import { AdminForthDataTypes, AdminForthFilterOperators, AdminForthSortDirections } from '../types/Common.js';
7+
import { afLogger } from '../modules/logger.js';
78

89
class ClickhouseConnector extends AdminForthBaseConnector implements IAdminForthDataSourceConnector {
910

@@ -95,7 +96,7 @@ class ClickhouseConnector extends AdminForthBaseConnector implements IAdminForth
9596
});
9697
rows = await q.json();
9798
} catch (e) {
98-
console.error(` 🛑Error connecting to datasource URL ${this.url}:`, e);
99+
afLogger.error(` 🛑Error connecting to datasource URL ${this.url}: ${e}`);
99100
return null;
100101
}
101102

@@ -169,7 +170,7 @@ class ClickhouseConnector extends AdminForthBaseConnector implements IAdminForth
169170
return {'error': `Failed to parse JSON: ${e.message}`}
170171
}
171172
} else {
172-
console.error(`AdminForth: JSON field is not a string but ${field._underlineType}, this is not supported yet`);
173+
afLogger.error(`AdminForth: JSON field is not a string but ${field._underlineType}, this is not supported yet`);
173174
}
174175
}
175176
return value;
@@ -197,7 +198,7 @@ class ClickhouseConnector extends AdminForthBaseConnector implements IAdminForth
197198
if (field._underlineType.startsWith('String') || field._underlineType.startsWith('FixedString')) {
198199
return JSON.stringify(value);
199200
} else {
200-
console.error(`AdminForth: JSON field is not a string/text but ${field._underlineType}, this is not supported yet`);
201+
afLogger.error(`AdminForth: JSON field is not a string/text but ${field._underlineType}, this is not supported yet`);
201202
}
202203
}
203204

adminforth/dataConnectors/mongo.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { MongoClient } from 'mongodb';
33
import { Decimal128, Double } from 'bson';
44
import { IAdminForthDataSourceConnector, IAdminForthSingleFilter, IAdminForthAndOrFilter, AdminForthResource } from '../types/Back.js';
55
import AdminForthBaseConnector from './baseConnector.js';
6-
6+
import { afLogger } from '../modules/logger.js';
77
import { AdminForthDataTypes, AdminForthFilterOperators, AdminForthSortDirections, } from '../types/Common.js';
88

99
const escapeRegex = (value) => {
@@ -36,11 +36,11 @@ class MongoConnector extends AdminForthBaseConnector implements IAdminForthDataS
3636
try {
3737
await this.client.connect();
3838
this.client.on('error', (err) => {
39-
console.log('Mongo error: ', err.message)
39+
afLogger.error(`Mongo error: ${err.message}`);
4040
});
41-
console.log('Connected to Mongo');
41+
afLogger.info('Connected to Mongo');
4242
} catch (e) {
43-
console.error(`Failed to connect to Mongo: ${e}`);
43+
afLogger.error(`Failed to connect to Mongo: ${e}`);
4444
}
4545
})();
4646
}
@@ -262,7 +262,7 @@ class MongoConnector extends AdminForthBaseConnector implements IAdminForthDataS
262262

263263
// explicitly ignore raw SQL filters for MongoDB
264264
if ((filter as IAdminForthSingleFilter).insecureRawSQL !== undefined) {
265-
console.warn('⚠️ Ignoring insecureRawSQL filter for MongoDB:', (filter as IAdminForthSingleFilter).insecureRawSQL);
265+
afLogger.warn(`⚠️ Ignoring insecureRawSQL filter for MongoDB:, ${(filter as IAdminForthSingleFilter).insecureRawSQL}`);
266266
return {};
267267
}
268268

adminforth/dataConnectors/mysql.ts

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { AdminForthResource, IAdminForthSingleFilter, IAdminForthAndOrFilter, IA
33
import { AdminForthDataTypes, AdminForthFilterOperators, AdminForthSortDirections, } from '../types/Common.js';
44
import AdminForthBaseConnector from './baseConnector.js';
55
import mysql from 'mysql2/promise';
6+
import { dbLogger, afLogger } from '../modules/logger.js';
67

78
class MysqlConnector extends AdminForthBaseConnector implements IAdminForthDataSourceConnector {
89

@@ -15,7 +16,7 @@ class MysqlConnector extends AdminForthBaseConnector implements IAdminForthDataS
1516
queueLimit: 0
1617
});
1718
} catch (e) {
18-
console.error(`Failed to connect to MySQL: ${e}`);
19+
afLogger.error(`Failed to connect to MySQL: ${e}`);
1920
}
2021
}
2122

@@ -175,8 +176,8 @@ class MysqlConnector extends AdminForthBaseConnector implements IAdminForthDataS
175176
} else if (typeof value === 'object') {
176177
return value;
177178
} else {
178-
console.error('JSON field value is not string or object, but has type:', typeof value);
179-
console.error('Field:', field);
179+
afLogger.error(`JSON field value is not string or object, but has type: ${typeof value}`);
180+
afLogger.error(`Field:, ${field}`);
180181
return {}
181182
}
182183
}
@@ -317,9 +318,9 @@ class MysqlConnector extends AdminForthBaseConnector implements IAdminForthDataS
317318
if (orderBy) selectQuery += ` ${orderBy}`;
318319
if (limit) selectQuery += ` LIMIT ${limit}`;
319320
if (offset) selectQuery += ` OFFSET ${offset}`;
320-
if (process.env.HEAVY_DEBUG_QUERY) {
321-
console.log('🪲📜 MySQL Q:', selectQuery, 'values:', filterValues);
322-
}
321+
322+
dbLogger.trace(`🪲📜 MySQL Q: ${selectQuery} values: ${JSON.stringify(filterValues)}`);
323+
323324
const [results] = await this.client.execute(selectQuery, filterValues);
324325
return results.map((row) => {
325326
const newRow = {};
@@ -341,9 +342,7 @@ class MysqlConnector extends AdminForthBaseConnector implements IAdminForthDataS
341342
}
342343
const { sql: where, values: filterValues } = this.whereClauseAndValues(filters);
343344
const q = `SELECT COUNT(*) FROM ${tableName} ${where}`;
344-
if (process.env.HEAVY_DEBUG_QUERY) {
345-
console.log('🪲📜 MySQL Q:', q, 'values:', filterValues);
346-
}
345+
dbLogger.trace(`🪲📜 MySQL Q: ${q} values: ${JSON.stringify(filterValues)}`);
347346
const [results] = await this.client.execute(q, filterValues);
348347
return +results[0]["COUNT(*)"];
349348
}
@@ -353,9 +352,7 @@ class MysqlConnector extends AdminForthBaseConnector implements IAdminForthDataS
353352
const result = {};
354353
await Promise.all(columns.map(async (col) => {
355354
const q = `SELECT MIN(${col.name}) as min, MAX(${col.name}) as max FROM ${tableName}`;
356-
if (process.env.HEAVY_DEBUG_QUERY) {
357-
console.log('🪲📜 MySQL Q:', q);
358-
}
355+
dbLogger.trace(`🪲📜 MySQL Q: ${q}`);
359356
const [results] = await this.client.execute(q);
360357
const { min, max } = results[0];
361358
result[col.name] = {
@@ -371,9 +368,7 @@ class MysqlConnector extends AdminForthBaseConnector implements IAdminForthDataS
371368
const placeholders = columns.map(() => '?').join(', ');
372369
const values = columns.map((colName) => typeof record[colName] === 'undefined' ? null : record[colName]);
373370
const q = `INSERT INTO ${tableName} (${columns.join(', ')}) VALUES (${placeholders})`;
374-
if (process.env.HEAVY_DEBUG_QUERY) {
375-
console.log('🪲📜 MySQL Q:', q, 'values:', values);
376-
}
371+
dbLogger.trace(`🪲📜 MySQL Q: ${q} values: ${JSON.stringify(values)}`);
377372
const ret = await this.client.execute(q, values);
378373
return ret.insertId;
379374
}
@@ -382,17 +377,13 @@ class MysqlConnector extends AdminForthBaseConnector implements IAdminForthDataS
382377
const values = [...Object.values(newValues), recordId];
383378
const columnsWithPlaceholders = Object.keys(newValues).map((col, i) => `${col} = ?`).join(', ');
384379
const q = `UPDATE ${resource.table} SET ${columnsWithPlaceholders} WHERE ${this.getPrimaryKey(resource)} = ?`;
385-
if (process.env.HEAVY_DEBUG_QUERY) {
386-
console.log('🪲📜 MySQL Q:', q, 'values:', values);
387-
}
380+
dbLogger.trace(`🪲📜 MySQL Q: ${q} values: ${JSON.stringify(values)}`);
388381
await this.client.execute(q, values);
389382
}
390383

391384
async deleteRecord({ resource, recordId }): Promise<boolean> {
392385
const q = `DELETE FROM ${resource.table} WHERE ${this.getPrimaryKey(resource)} = ?`;
393-
if (process.env.HEAVY_DEBUG_QUERY) {
394-
console.log('🪲📜 MySQL Q:', q, 'values:', [recordId]);
395-
}
386+
dbLogger.trace(`🪲📜 MySQL Q: ${q} values: ${JSON.stringify([recordId])}`);
396387
const res = await this.client.execute(q, [recordId]);
397388
return res.rowCount > 0;
398389
}

0 commit comments

Comments
 (0)