badmfck-api-server 3.8.1 → 3.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,10 @@ export interface APIServiceNetworkLogItem {
22
22
  };
23
23
  error?: string | null;
24
24
  }
25
- export interface APIServiceOptions {
25
+ export interface IInterceptor<T> {
26
+ intercept(req: HTTPRequestVO<any>): Promise<T | IError>;
27
+ }
28
+ export interface APIServiceOptions<TInterceptor = unknown> {
26
29
  port: number;
27
30
  baseEndPoint: string;
28
31
  corsHostWhiteList: string[];
@@ -32,7 +35,7 @@ export interface APIServiceOptions {
32
35
  onNetworkLog?: ((log: APIServiceNetworkLogItem) => void) | null;
33
36
  onError?: ((...rest: any[]) => void) | null;
34
37
  isProductionEnvironment: boolean;
35
- interceptor?: IBaseEndpoint;
38
+ interceptor?: IInterceptor<TInterceptor>;
36
39
  postproducer?: (req: HTTPRequestVO | undefined | null, res: Response, data: TransferPacketVO<any>, requestTime: number, endpoint?: string, log?: APIServiceNetworkLogItem | null) => Promise<TransferPacketVO>;
37
40
  preproducer?: (req: HTTPRequestVO | undefined | null) => any;
38
41
  access: {
@@ -44,7 +47,10 @@ export interface APIServiceOptions {
44
47
  fileTempDir: string;
45
48
  fileLimit: number;
46
49
  }
47
- export declare function getDefaultOptions(): APIServiceOptions;
50
+ type InferInterceptor<T> = T extends IInterceptor<infer U> ? U : unknown;
51
+ export declare function getDefaultOptions<I extends IInterceptor<any> | undefined>(opts: Omit<APIServiceOptions<InferInterceptor<NonNullable<I>>>, 'interceptor'> & {
52
+ interceptor?: I;
53
+ }): APIServiceOptions<InferInterceptor<NonNullable<I>>>;
48
54
  export declare const REQ_CREATE_NET_LOG: Req<void, APIServiceNetworkLogItem>;
49
55
  export declare const REQ_HTTP_LOG: Req<void, APIServiceNetworkLogItem[]>;
50
56
  export declare const REQ_HTTP_REQUESTS_COUNT: Req<void, number>;
@@ -64,8 +70,9 @@ export declare class APIService extends BaseService {
64
70
  private started;
65
71
  private requestsCount;
66
72
  netLog: APIServiceNetworkLogItem[];
67
- constructor(options?: APIServiceOptions | null);
73
+ constructor(options: APIServiceOptions);
68
74
  init(): Promise<void>;
69
75
  sendResponse(ref: string, res: Response, data: TransferPacketVO<any>, requestTime: number, endpoint?: string, log?: APIServiceNetworkLogItem | null, req?: HTTPRequestVO): Promise<void>;
70
76
  checkDataLength(data: any, result?: any, lvl?: number): any;
71
77
  }
78
+ export {};
@@ -47,7 +47,10 @@ const MonitorService_1 = require("./MonitorService");
47
47
  const MysqlAdapter_1 = require("./db/MysqlAdapter");
48
48
  const DocumentService_1 = require("./DocumentService");
49
49
  const Documentation_1 = require("./documentation/Documentation");
50
- function getDefaultOptions() {
50
+ function bindRequestToOptions(opts, req) {
51
+ return req;
52
+ }
53
+ function getDefaultOptions(opts) {
51
54
  return {
52
55
  port: 8091,
53
56
  access: {
@@ -95,7 +98,7 @@ async function Initializer(services) {
95
98
  exports.Initializer = Initializer;
96
99
  class APIService extends BaseService_1.BaseService {
97
100
  static nextLogID = 0;
98
- version = "3.8.1";
101
+ version = "3.8.3";
99
102
  options;
100
103
  monitor = null;
101
104
  started = new Date();
@@ -103,7 +106,7 @@ class APIService extends BaseService_1.BaseService {
103
106
  netLog = [];
104
107
  constructor(options) {
105
108
  super('HTTP Service');
106
- this.options = options ?? getDefaultOptions();
109
+ this.options = options;
107
110
  if (!this.options.corsHostWhiteList)
108
111
  this.options.corsHostWhiteList = [];
109
112
  const self = "http://localhost:" + this.options.port;
@@ -233,7 +236,7 @@ class APIService extends BaseService_1.BaseService {
233
236
  body[i] = req.query[i];
234
237
  }
235
238
  }
236
- const httpRequest = {
239
+ let httpRequest = {
237
240
  raw: req,
238
241
  response: res,
239
242
  method: req.method,
@@ -286,12 +289,14 @@ class APIService extends BaseService_1.BaseService {
286
289
  if (!ignoreInterceptor) {
287
290
  let interceptorResult;
288
291
  if (this.options.interceptor) {
289
- interceptorResult = await this.options.interceptor.__execute(httpRequest);
290
- if (interceptorResult.error && !allowInterceptorError) {
292
+ const httpRequestBound = bindRequestToOptions(this.options, httpRequest);
293
+ interceptorResult = await this.options.interceptor.intercept(httpRequest);
294
+ if (DefaultErrors_1.ErrorUtils.isError(interceptorResult) && !allowInterceptorError) {
291
295
  this.sendResponse(req.get("Referer") ?? "", res, interceptorResult, tme, ep, log, httpRequest);
292
296
  return;
293
297
  }
294
- httpRequest.interceptorResult = interceptorResult;
298
+ httpRequestBound.interceptorResult = interceptorResult;
299
+ httpRequest = httpRequestBound;
295
300
  }
296
301
  }
297
302
  const precheck = await i.__precheck(httpRequest);
@@ -42,9 +42,8 @@ class TimeframeService extends BaseService_1.BaseService {
42
42
  super("TimeframeService");
43
43
  }
44
44
  async init() {
45
- super.init();
46
45
  exports.REQ_TIMEFRAME_TASK_ADD.listener = async (req) => {
47
- (0, LogService_1.logInfo)("Add tack to TimeframeService: " + req.name);
46
+ (0, LogService_1.logInfo)("Add tack " + req.name);
48
47
  this.tasks.push(req);
49
48
  };
50
49
  this.intervalId = setInterval(() => {
@@ -63,14 +62,14 @@ class TimeframeService extends BaseService_1.BaseService {
63
62
  if (now >= task.start && (!task.executed || task.executed < task.start)) {
64
63
  if (now - task.start <= this.GRACE_WINDOW_MS) {
65
64
  try {
66
- (0, LogService_1.logInfo)("Timeframe Servie - execute task ", task.name);
65
+ (0, LogService_1.logInfo)("Execute task ", task.name);
67
66
  if (task.callback.length > 0 && task.params)
68
67
  task.callback(task.params);
69
68
  else
70
69
  task.callback();
71
70
  task.executed = Date.now();
72
71
  task.retries = 0;
73
- (0, LogService_1.logInfo)("Timeframe Servie - task executed ", task.name);
72
+ (0, LogService_1.logInfo)("Executed task ", task.name);
74
73
  if (task.repeat) {
75
74
  task.start += task.repeat;
76
75
  }
@@ -48,6 +48,7 @@ export declare class MysqlAdapter implements IDBAdapter {
48
48
  query(request: IDBQuery, conn?: mysql.PoolConnection): Promise<IDBResult>;
49
49
  finalizeConnection(conn: mysql.PoolConnection): void;
50
50
  prepareQuery(request: IDBQuery): string;
51
+ static safeReplace(query: string, key: string, value: string): string;
51
52
  static prepareQueryFieldValue(field: IDBQueryField): string | number | boolean | null | undefined;
52
53
  prepareCountQuery(query: string): string;
53
54
  commit(trx: ITransaction): Promise<IDBError | null>;
@@ -519,7 +519,7 @@ class MysqlAdapter {
519
519
  queryField.name = name.replaceAll("`", '').replaceAll('\"', "").replaceAll('\'', "");
520
520
  fields[i] = queryField;
521
521
  const parsed = MysqlAdapter.prepareQueryFieldValue(fields[i]);
522
- query = query.replaceAll("@" + name, parsed + "");
522
+ query = MysqlAdapter.safeReplace(query, "@" + name, parsed + "");
523
523
  }
524
524
  }
525
525
  const tmp = query.toLowerCase();
@@ -538,9 +538,8 @@ class MysqlAdapter {
538
538
  insertFieldNames.push('`' + f.name + '`');
539
539
  insertFieldValues.push(f.__parsedValue);
540
540
  }
541
- query = query
542
- .replaceAll('@fields', insertFieldNames.join(","))
543
- .replaceAll('@values', insertFieldValues.join(","));
541
+ query = MysqlAdapter.safeReplace(query, "@fields", insertFieldNames.join(","));
542
+ query = MysqlAdapter.safeReplace(query, "@values", insertFieldValues.join(","));
544
543
  }
545
544
  if (query.indexOf("@insert") !== -1) {
546
545
  let oninsertNames = [];
@@ -554,7 +553,7 @@ class MysqlAdapter {
554
553
  oninsertNames.push(f.name);
555
554
  oninsertValues.push(f.__parsedValue);
556
555
  }
557
- query = query.replaceAll("@insert", `(${oninsertNames.join(",")}) VALUES (${oninsertValues.join(",")})`);
556
+ query = MysqlAdapter.safeReplace(query, "@insert", `(${oninsertNames.join(",")}) VALUES (${oninsertValues.join(",")})`);
558
557
  }
559
558
  if (query.indexOf("@onupdate") !== -1) {
560
559
  let onUpdate = [];
@@ -566,7 +565,7 @@ class MysqlAdapter {
566
565
  continue;
567
566
  onUpdate.push('`' + f.name + '` = ' + f.__parsedValue);
568
567
  }
569
- query = query.replaceAll("@onupdate", onUpdate.join(" , "));
568
+ query = MysqlAdapter.safeReplace(query, "@onupdate", onUpdate.join(" , "));
570
569
  }
571
570
  if (query.indexOf('@onduplicate') !== -1) {
572
571
  let onDuplicate = [];
@@ -578,10 +577,14 @@ class MysqlAdapter {
578
577
  continue;
579
578
  onDuplicate.push('`' + f.name + '` = ' + f.__parsedValue);
580
579
  }
581
- query = query.replaceAll("@onduplicate", onDuplicate.join(" , "));
580
+ query = MysqlAdapter.safeReplace(query, "@onduplicate", onDuplicate.join(" , "));
582
581
  }
583
582
  return query;
584
583
  }
584
+ static safeReplace(query, key, value) {
585
+ const regex = new RegExp(key + "(?=\\b|\\s|,|\\)|$)", "g");
586
+ return query.replace(regex, value);
587
+ }
585
588
  static prepareQueryFieldValue(field) {
586
589
  let value = field.value;
587
590
  let system = field.system;
@@ -18,7 +18,7 @@ export interface TransferPacketVO<T = any> {
18
18
  blockResponse?: boolean;
19
19
  project?: string;
20
20
  }
21
- export interface HTTPRequestVO<T = any> {
21
+ export interface HTTPRequestVO<T = any, TInterceport = any> {
22
22
  raw: any;
23
23
  response: any;
24
24
  method: string;
@@ -30,7 +30,7 @@ export interface HTTPRequestVO<T = any> {
30
30
  [key: string]: string;
31
31
  };
32
32
  endpoint: string;
33
- interceptorResult?: TransferPacketVO<any>;
33
+ interceptorResult?: any;
34
34
  preproducerResult?: any;
35
35
  precheck?: TransferPacketVO<any> | null;
36
36
  files: FileArray | null | undefined;
package/dist/index.d.ts CHANGED
@@ -10,4 +10,5 @@ import { UID } from "./apiServer/helper/UID";
10
10
  import { ExternalService } from "./apiServer/external/ExternalService";
11
11
  import { DBService } from "./apiServer/DBService";
12
12
  import { YYYYMMDDHH } from "./apiServer/helper/YYYYMMDDHH";
13
- export { UID, YYYYMMDDHH, APIService, Initializer, LocalRequest, ValidationModel, MysqlService, Validator, LogService, DataProvider, ErrorUtils, ExternalService, DBService, S_MONITOR_REGISTRATE_ACTION };
13
+ import { TimeframeService } from "./apiServer/TimeframeService";
14
+ export { UID, YYYYMMDDHH, APIService, Initializer, LocalRequest, ValidationModel, MysqlService, TimeframeService, Validator, LogService, DataProvider, ErrorUtils, ExternalService, DBService, S_MONITOR_REGISTRATE_ACTION };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.S_MONITOR_REGISTRATE_ACTION = exports.DBService = exports.ExternalService = exports.ErrorUtils = exports.DataProvider = exports.LogService = exports.Validator = exports.MysqlService = exports.LocalRequest = exports.Initializer = exports.APIService = exports.YYYYMMDDHH = exports.UID = void 0;
3
+ exports.S_MONITOR_REGISTRATE_ACTION = exports.DBService = exports.ExternalService = exports.ErrorUtils = exports.DataProvider = exports.LogService = exports.Validator = exports.TimeframeService = exports.MysqlService = exports.LocalRequest = exports.Initializer = exports.APIService = exports.YYYYMMDDHH = exports.UID = 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; } });
@@ -26,3 +26,5 @@ const DBService_1 = require("./apiServer/DBService");
26
26
  Object.defineProperty(exports, "DBService", { enumerable: true, get: function () { return DBService_1.DBService; } });
27
27
  const YYYYMMDDHH_1 = require("./apiServer/helper/YYYYMMDDHH");
28
28
  Object.defineProperty(exports, "YYYYMMDDHH", { enumerable: true, get: function () { return YYYYMMDDHH_1.YYYYMMDDHH; } });
29
+ const TimeframeService_1 = require("./apiServer/TimeframeService");
30
+ Object.defineProperty(exports, "TimeframeService", { enumerable: true, get: function () { return TimeframeService_1.TimeframeService; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "badmfck-api-server",
3
- "version": "3.8.1",
3
+ "version": "3.8.3",
4
4
  "description": "Simple API http server based on express",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",