badmfck-api-server 1.3.5 → 1.3.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -10,6 +10,7 @@ const cors_1 = __importDefault(require("cors"));
10
10
  const BaseEndpoint_1 = require("./BaseEndpoint");
11
11
  const DefaultErrors_1 = __importDefault(require("./structures/DefaultErrors"));
12
12
  const badmfck_signal_1 = require("badmfck-signal");
13
+ const LogService_1 = require("./LogService");
13
14
  function getDefaultOptions() {
14
15
  return {
15
16
  port: 8091,
@@ -20,10 +21,10 @@ function getDefaultOptions() {
20
21
  endpoints: [],
21
22
  jsonLimit: "10mb",
22
23
  onNetworkLog: function (log) {
23
- console.log(log);
24
+ (0, LogService_1.logInfo)(log);
24
25
  },
25
26
  onError: function (err) {
26
- console.error.call(this, err);
27
+ (0, LogService_1.logError)(err);
27
28
  },
28
29
  isProductionEnvironment: false
29
30
  };
@@ -42,7 +43,7 @@ async function Initializer(services) {
42
43
  exports.Initializer = Initializer;
43
44
  class APIService extends BaseService_1.BaseService {
44
45
  static nextLogID = 0;
45
- version = "1.2.9";
46
+ version = "1.3.6";
46
47
  options;
47
48
  netLog = [];
48
49
  constructor(options) {
@@ -5,38 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.LocalRequest = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
- axios_1.default.interceptors.request.use((x) => {
9
- console.log(`AXIOS REQ:\n\turl:${x.url}\n\tmethod: ${x.method}\n\tdata: ${(() => {
10
- if (typeof x.data === "string")
11
- return x.data;
12
- return JSON.stringify(x.data, null, "\t\t");
13
- })()}\n\theaders:\n${(() => {
14
- let h = "";
15
- for (let i in x.headers) {
16
- if (h !== "")
17
- h += "\n";
18
- h += "\t\t" + i + " = " + x.headers[i];
19
- }
20
- return h;
21
- })()}`);
22
- return x;
23
- });
24
- axios_1.default.interceptors.response.use((x) => {
25
- console.log(`AXIOS RESP:\n\tdata: ${(() => {
26
- if (typeof x.data === "string")
27
- return x.data;
28
- return JSON.stringify(x.data, null, "\t\t");
29
- })()}\n\theaders:\n${(() => {
30
- let h = "";
31
- for (let i in x.headers) {
32
- if (h !== "")
33
- h += "\n";
34
- h += "\t\t" + i + " = " + x.headers[i];
35
- }
36
- return h;
37
- })()}`);
38
- return x;
39
- });
40
8
  const LocalRequest = async (ep, data, method, headers) => {
41
9
  let m = "get";
42
10
  if (method)
@@ -0,0 +1,38 @@
1
+ import Signal, { Req } from "badmfck-signal";
2
+ import { BaseService } from "./BaseService";
3
+ export type ILogItemLevel = "info" | "error" | "warn" | "crit";
4
+ export interface ILogItem {
5
+ id: number;
6
+ level: ILogItemLevel;
7
+ time: number;
8
+ text: string;
9
+ date: string;
10
+ }
11
+ export interface ILogServiceOptions {
12
+ output?: (data?: any) => void;
13
+ stackSize: number;
14
+ }
15
+ export declare const getDefaultLogOptions: () => ILogServiceOptions;
16
+ export declare const logInfo: (message: any, ...optional: any[]) => void;
17
+ export declare const logWarn: (message: any, ...optional: any[]) => void;
18
+ export declare const logCrit: (message: any, ...optional: any[]) => void;
19
+ export declare const logError: (message: any, ...optional: any[]) => void;
20
+ export declare const S_LOG: Signal<{
21
+ level: ILogItemLevel;
22
+ data: any[];
23
+ }>;
24
+ export declare const S_LOG_CREATED: Signal<ILogItem>;
25
+ export declare const S_LOG_CHANGE_LEVEL: Signal<ILogItemLevel | "all">;
26
+ export declare const S_LOG_FLUSH: Signal<void>;
27
+ export declare const REQ_LOG: Req<void, ILogItem[]>;
28
+ export declare class LogService extends BaseService {
29
+ epoch: number;
30
+ log: ILogItem[];
31
+ options: ILogServiceOptions;
32
+ level: "all" | ILogItemLevel;
33
+ constructor(opt?: ILogServiceOptions);
34
+ init(): Promise<void>;
35
+ createDate(d?: Date): string;
36
+ leadZero(num: number): string;
37
+ createText(data: any): string;
38
+ }
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.LogService = exports.REQ_LOG = exports.S_LOG_FLUSH = exports.S_LOG_CHANGE_LEVEL = exports.S_LOG_CREATED = exports.S_LOG = exports.logError = exports.logCrit = exports.logWarn = exports.logInfo = exports.getDefaultLogOptions = void 0;
27
+ const badmfck_signal_1 = __importStar(require("badmfck-signal"));
28
+ const BaseService_1 = require("./BaseService");
29
+ const getDefaultLogOptions = () => {
30
+ return {
31
+ stackSize: 1000
32
+ };
33
+ };
34
+ exports.getDefaultLogOptions = getDefaultLogOptions;
35
+ const logInfo = (message, ...optional) => { exports.S_LOG.invoke({ level: "info", data: [message, optional] }); };
36
+ exports.logInfo = logInfo;
37
+ const logWarn = (message, ...optional) => { exports.S_LOG.invoke({ level: "warn", data: [message, optional] }); };
38
+ exports.logWarn = logWarn;
39
+ const logCrit = (message, ...optional) => { exports.S_LOG.invoke({ level: "crit", data: [message, optional] }); };
40
+ exports.logCrit = logCrit;
41
+ const logError = (message, ...optional) => { exports.S_LOG.invoke({ level: "error", data: [message, optional] }); };
42
+ exports.logError = logError;
43
+ exports.S_LOG = new badmfck_signal_1.default();
44
+ exports.S_LOG_CREATED = new badmfck_signal_1.default();
45
+ exports.S_LOG_CHANGE_LEVEL = new badmfck_signal_1.default();
46
+ exports.S_LOG_FLUSH = new badmfck_signal_1.default();
47
+ exports.REQ_LOG = new badmfck_signal_1.Req();
48
+ class LogService extends BaseService_1.BaseService {
49
+ epoch = 1699476234961;
50
+ log = [];
51
+ options;
52
+ level = "all";
53
+ constructor(opt) {
54
+ super("LogService");
55
+ if (!opt)
56
+ opt = (0, exports.getDefaultLogOptions)();
57
+ this.options = opt;
58
+ }
59
+ async init() {
60
+ super.init();
61
+ exports.REQ_LOG.listener = async () => [...this.log];
62
+ exports.S_LOG_CHANGE_LEVEL.subscribe(l => { this.level = l; });
63
+ exports.S_LOG_FLUSH.subscribe(() => this.log = []);
64
+ exports.S_LOG.subscribe((log) => {
65
+ if (log.level !== this.level) {
66
+ if (this.level !== "all")
67
+ return;
68
+ }
69
+ const msg = log.data[0];
70
+ const optional = log.data[1];
71
+ let text = this.createText(msg);
72
+ if (optional) {
73
+ for (let i of optional)
74
+ text += ", " + this.createText(optional);
75
+ }
76
+ const d = new Date();
77
+ const logitem = {
78
+ level: log.level,
79
+ id: ((+new Date()) - this.epoch),
80
+ text: text,
81
+ time: d.getTime(),
82
+ date: this.createDate(d)
83
+ };
84
+ if (this.options.output)
85
+ this.options.output(logitem.level + " > " + logitem.id.toString(16) + " > " + logitem.date + " > " + text);
86
+ exports.S_LOG_CREATED.invoke(logitem);
87
+ this.log.push(logitem);
88
+ let limit = this.options.stackSize ?? 1000;
89
+ if (limit > 10000)
90
+ limit = 10000;
91
+ if (this.log.length > limit)
92
+ this.log.shift();
93
+ });
94
+ }
95
+ createDate(d) {
96
+ if (!d)
97
+ d = new Date();
98
+ return d.getFullYear() + "-" + this.leadZero(d.getMonth() + 1) + "-" + this.leadZero(d.getDate()) + " " + this.leadZero(d.getHours()) + ":" + this.leadZero(d.getMinutes()) + ":" + this.leadZero(d.getSeconds());
99
+ }
100
+ leadZero(num) {
101
+ if (num < 10)
102
+ return "0" + num;
103
+ return num + "";
104
+ }
105
+ createText(data) {
106
+ if (data === null)
107
+ return "null";
108
+ if (data === undefined)
109
+ return "undefined";
110
+ let res = "";
111
+ if (typeof data === "object") {
112
+ if ("toString" in data && data.toString && typeof data.toString === "function") {
113
+ res = data.toString();
114
+ }
115
+ else {
116
+ try {
117
+ const tmp = JSON.stringify(data, null, "\t");
118
+ res = tmp ?? "";
119
+ }
120
+ catch (e) {
121
+ res = `${data}`;
122
+ }
123
+ }
124
+ }
125
+ else {
126
+ res = data + "";
127
+ }
128
+ if (res.length > 1024)
129
+ res = res.substring(0, 1024) + "... (total: " + res.length + ")";
130
+ return res;
131
+ }
132
+ }
133
+ exports.LogService = LogService;
@@ -10,7 +10,6 @@ export interface MysqlServiceOptions {
10
10
  password: string;
11
11
  port: number;
12
12
  database: string;
13
- onLog?: (level: number, data: any) => void;
14
13
  }
15
14
  export interface MysqlResult {
16
15
  error?: MysqlError | null;
@@ -8,6 +8,7 @@ const mysql_1 = __importDefault(require("mysql"));
8
8
  const BaseService_1 = require("./BaseService");
9
9
  const badmfck_signal_1 = require("badmfck-signal");
10
10
  const crypto_1 = require("crypto");
11
+ const LogService_1 = require("./LogService");
11
12
  exports.REQ_MYSQL_QUERY = new badmfck_signal_1.Req("REQ_MYSQL_QUERY");
12
13
  const executeQuery = async (query) => { return await exports.REQ_MYSQL_QUERY.request(query); };
13
14
  exports.executeQuery = executeQuery;
@@ -47,21 +48,18 @@ class MysqlService extends BaseService_1.BaseService {
47
48
  };
48
49
  }
49
50
  async recreatePool() {
50
- if (this.options.onLog)
51
- this.options.onLog(1, "Mysql server trying to create pool");
51
+ (0, LogService_1.logInfo)("Mysql server trying to create pool");
52
52
  this.serviceStarted = false;
53
53
  const ok = await this.createPool();
54
54
  if (!ok) {
55
- if (this.options.onLog)
56
- this.options.onLog(2, "Mysql server not connected, retrying in 3 sec");
55
+ (0, LogService_1.logWarn)("Mysql server not connected, retrying in 3 sec");
57
56
  if (this.timeoutID)
58
57
  clearTimeout(this.timeoutID);
59
58
  this.timeoutID = setTimeout(() => { this.recreatePool(); }, 3000);
60
59
  }
61
60
  else {
62
61
  this.serviceStarted = true;
63
- if (this.options.onLog)
64
- this.options.onLog(1, "Mysql Service started!");
62
+ (0, LogService_1.logInfo)("Mysql Service started!");
65
63
  }
66
64
  }
67
65
  async onApplicationReady() { }
@@ -134,8 +132,7 @@ class MysqlService extends BaseService_1.BaseService {
134
132
  async execute(query) {
135
133
  return new Promise((resolve, reject) => {
136
134
  if (!this.pool) {
137
- if (this.options.onLog)
138
- this.options.onLog(2, "No pool");
135
+ (0, LogService_1.logError)("No pool");
139
136
  resolve({
140
137
  error: {
141
138
  code: "NO_POOL",
@@ -152,8 +149,7 @@ class MysqlService extends BaseService_1.BaseService {
152
149
  }
153
150
  this.pool.getConnection((err, conn) => {
154
151
  if (err) {
155
- if (this.options.onLog)
156
- this.options.onLog(2, `${err}`);
152
+ (0, LogService_1.logError)(err);
157
153
  if (`${err}`.indexOf('ECONNREFUSED') !== -1) {
158
154
  this.recreatePool();
159
155
  }
@@ -165,8 +161,7 @@ class MysqlService extends BaseService_1.BaseService {
165
161
  return;
166
162
  }
167
163
  if (!conn) {
168
- if (this.options.onLog)
169
- this.options.onLog(2, `NO_CONN`);
164
+ (0, LogService_1.logCrit)(`No connection created!`);
170
165
  resolve({
171
166
  error: {
172
167
  code: "NO_CONN",
@@ -189,8 +184,7 @@ class MysqlService extends BaseService_1.BaseService {
189
184
  conn.release();
190
185
  }
191
186
  catch (e) { }
192
- if (this.options.onLog)
193
- this.options.onLog(2, "QUERY_ERR " + e);
187
+ (0, LogService_1.logError)("QUERY_ERR: " + e);
194
188
  resolve({
195
189
  error: {
196
190
  code: "QUERY_ERR",
@@ -213,8 +207,7 @@ class MysqlService extends BaseService_1.BaseService {
213
207
  errCatched = true;
214
208
  conn.release();
215
209
  conn.removeAllListeners();
216
- if (this.options.onLog)
217
- this.options.onLog(2, `${err}`);
210
+ (0, LogService_1.logError)(err);
218
211
  conn.removeAllListeners();
219
212
  resolve({
220
213
  error: {
@@ -229,8 +222,7 @@ class MysqlService extends BaseService_1.BaseService {
229
222
  fields: null
230
223
  });
231
224
  });
232
- if (this.options.onLog)
233
- this.options.onLog(0, query);
225
+ (0, LogService_1.logInfo)(query);
234
226
  conn.query(query, (err, results, fields) => {
235
227
  conn.release();
236
228
  conn.removeAllListeners();
@@ -238,8 +230,7 @@ class MysqlService extends BaseService_1.BaseService {
238
230
  return;
239
231
  if (err) {
240
232
  const dup = `${err}`.toLowerCase().indexOf("er_dup_entry") !== -1;
241
- if (this.options.onLog)
242
- this.options.onLog(2, `${err}`);
233
+ (0, LogService_1.logError)(err);
243
234
  resolve({
244
235
  error: err,
245
236
  data: null,
@@ -257,20 +248,18 @@ class MysqlService extends BaseService_1.BaseService {
257
248
  });
258
249
  }
259
250
  async createPool() {
260
- if (this.options.onLog)
261
- this.options.onLog(1, "Connecting to mysql: \n HOST: " + this.options.host + '\n PORT:' + this.options.port);
251
+ (0, LogService_1.logInfo)("Connecting to mysql: \n HOST: " + this.options.host + '\n PORT:' + this.options.port);
262
252
  let err = false;
263
253
  if (this.pool) {
264
254
  try {
265
255
  this.pool.removeAllListeners();
266
256
  this.pool.end(err => {
267
- if (err && this.options.onLog)
268
- this.options.onLog(2, err);
257
+ if (err)
258
+ (0, LogService_1.logError)(err);
269
259
  });
270
260
  }
271
261
  catch (e) {
272
- if (this.options.onLog)
273
- this.options.onLog(2, e);
262
+ (0, LogService_1.logCrit)(e);
274
263
  }
275
264
  }
276
265
  try {
@@ -285,14 +274,12 @@ class MysqlService extends BaseService_1.BaseService {
285
274
  });
286
275
  }
287
276
  catch (e) {
288
- if (this.options.onLog)
289
- this.options.onLog(2, "Can't connect to MYSQL!");
277
+ (0, LogService_1.logCrit)("Can't connect to MYSQL!");
290
278
  err = true;
291
279
  }
292
280
  if (!err && this.pool) {
293
281
  this.pool.on("error", (evt) => {
294
- if (this.options.onLog)
295
- this.options.onLog(2, `${evt}`);
282
+ (0, LogService_1.logError)(evt);
296
283
  });
297
284
  }
298
285
  return new Promise((res, rej) => {
@@ -306,8 +293,7 @@ class MysqlService extends BaseService_1.BaseService {
306
293
  }
307
294
  this.pool.getConnection((e, cnn) => {
308
295
  if (e) {
309
- if (this.options.onLog)
310
- this.options.onLog(2, e.message);
296
+ (0, LogService_1.logError)(e.message);
311
297
  res(false);
312
298
  return;
313
299
  }
package/dist/index.d.ts CHANGED
@@ -2,4 +2,5 @@ import { APIService, Initializer } from "./apiServer/APIService";
2
2
  import { LocalRequest } from "./apiServer/LocalRequest";
3
3
  import { MysqlService } from "./apiServer/MysqlService";
4
4
  import { Validator } from "./apiServer/helper/Validator";
5
- export { APIService, Initializer, LocalRequest, MysqlService, Validator };
5
+ import { LogService } from "./apiServer/LogService";
6
+ export { APIService, Initializer, LocalRequest, MysqlService, Validator, LogService };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Validator = exports.MysqlService = exports.LocalRequest = exports.Initializer = exports.APIService = void 0;
3
+ exports.LogService = exports.Validator = exports.MysqlService = exports.LocalRequest = exports.Initializer = exports.APIService = void 0;
4
4
  const APIService_1 = require("./apiServer/APIService");
5
5
  Object.defineProperty(exports, "APIService", { enumerable: true, get: function () { return APIService_1.APIService; } });
6
6
  Object.defineProperty(exports, "Initializer", { enumerable: true, get: function () { return APIService_1.Initializer; } });
@@ -10,3 +10,5 @@ const MysqlService_1 = require("./apiServer/MysqlService");
10
10
  Object.defineProperty(exports, "MysqlService", { enumerable: true, get: function () { return MysqlService_1.MysqlService; } });
11
11
  const Validator_1 = require("./apiServer/helper/Validator");
12
12
  Object.defineProperty(exports, "Validator", { enumerable: true, get: function () { return Validator_1.Validator; } });
13
+ const LogService_1 = require("./apiServer/LogService");
14
+ Object.defineProperty(exports, "LogService", { enumerable: true, get: function () { return LogService_1.LogService; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "badmfck-api-server",
3
- "version": "1.3.5",
3
+ "version": "1.3.6",
4
4
  "description": "Simple API http server based on express",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",