axe-api 1.0.0-rc3 → 1.0.0-rc5

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.
Files changed (40) hide show
  1. package/build/index.d.ts +2 -1
  2. package/build/index.js +3 -1
  3. package/build/src/Builders/ModelTreeBuilder.js +1 -2
  4. package/build/src/Builders/RouterBuilder.d.ts +1 -1
  5. package/build/src/Builders/RouterBuilder.js +4 -5
  6. package/build/src/Enums.d.ts +0 -7
  7. package/build/src/Enums.js +14 -22
  8. package/build/src/Handlers/RequestHandler.js +33 -25
  9. package/build/src/Helpers.d.ts +0 -1
  10. package/build/src/Helpers.js +1 -53
  11. package/build/src/Interfaces.d.ts +40 -6
  12. package/build/src/Middlewares/RateLimit/AdaptorFactory.d.ts +6 -0
  13. package/build/src/Middlewares/RateLimit/AdaptorFactory.js +17 -0
  14. package/build/src/Middlewares/RateLimit/IAdaptor.d.ts +6 -0
  15. package/build/src/Middlewares/RateLimit/IAdaptor.js +2 -0
  16. package/build/src/Middlewares/RateLimit/MemoryAdaptor.d.ts +10 -0
  17. package/build/src/Middlewares/RateLimit/MemoryAdaptor.js +41 -0
  18. package/build/src/Middlewares/RateLimit/RedisAdaptor.d.ts +11 -0
  19. package/build/src/Middlewares/RateLimit/RedisAdaptor.js +35 -0
  20. package/build/src/Middlewares/RateLimit/index.d.ts +6 -0
  21. package/build/src/Middlewares/RateLimit/index.js +118 -0
  22. package/build/src/Phases/ForceDelete/PreparePhase.js +1 -3
  23. package/build/src/Resolvers/ModelResolver.js +9 -4
  24. package/build/src/Resolvers/VersionResolver.js +1 -2
  25. package/build/src/Server.js +10 -9
  26. package/build/src/Services/APIService.js +10 -2
  27. package/build/src/Services/App.d.ts +6 -6
  28. package/build/src/Services/App.js +53 -10
  29. package/build/src/Services/ConverterService.d.ts +5 -0
  30. package/build/src/Services/ConverterService.js +26 -0
  31. package/build/src/Services/LogService.d.ts +8 -12
  32. package/build/src/Services/LogService.js +16 -33
  33. package/build/src/Services/ModelService.d.ts +3 -3
  34. package/build/src/Services/SchemaValidatorService.js +1 -2
  35. package/build/src/Services/URLService.d.ts +2 -2
  36. package/build/src/Services/URLService.js +23 -4
  37. package/build/src/Types.d.ts +13 -4
  38. package/build/src/constants.d.ts +1 -11
  39. package/build/src/constants.js +51 -52
  40. package/package.json +22 -20
package/build/index.d.ts CHANGED
@@ -3,6 +3,7 @@ import Model from "./src/Model";
3
3
  import ApiError from "./src/Exceptions/ApiError";
4
4
  import { DEFAULT_HANDLERS, DEFAULT_VERSION_CONFIG } from "./src/constants";
5
5
  import { IoCService, allow, deny, App, AxeRequest, AxeResponse } from "./src/Services";
6
+ import { rateLimit } from "./src/Middlewares/RateLimit";
6
7
  export * from "./src/Enums";
7
8
  export * from "./src/Interfaces";
8
- export { App, AxeRequest, AxeResponse, Server, Model, ApiError, DEFAULT_HANDLERS, DEFAULT_VERSION_CONFIG, IoCService, allow, deny, };
9
+ export { App, AxeRequest, AxeResponse, Server, Model, ApiError, DEFAULT_HANDLERS, DEFAULT_VERSION_CONFIG, IoCService, allow, deny, rateLimit, };
package/build/index.js CHANGED
@@ -17,7 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.deny = exports.allow = exports.IoCService = exports.DEFAULT_VERSION_CONFIG = exports.DEFAULT_HANDLERS = exports.ApiError = exports.Model = exports.Server = exports.AxeResponse = exports.AxeRequest = exports.App = void 0;
20
+ exports.rateLimit = exports.deny = exports.allow = exports.IoCService = exports.DEFAULT_VERSION_CONFIG = exports.DEFAULT_HANDLERS = exports.ApiError = exports.Model = exports.Server = exports.AxeResponse = exports.AxeRequest = exports.App = void 0;
21
21
  const Server_1 = __importDefault(require("./src/Server"));
22
22
  exports.Server = Server_1.default;
23
23
  const Model_1 = __importDefault(require("./src/Model"));
@@ -34,5 +34,7 @@ Object.defineProperty(exports, "deny", { enumerable: true, get: function () { re
34
34
  Object.defineProperty(exports, "App", { enumerable: true, get: function () { return Services_1.App; } });
35
35
  Object.defineProperty(exports, "AxeRequest", { enumerable: true, get: function () { return Services_1.AxeRequest; } });
36
36
  Object.defineProperty(exports, "AxeResponse", { enumerable: true, get: function () { return Services_1.AxeResponse; } });
37
+ const RateLimit_1 = require("./src/Middlewares/RateLimit");
38
+ Object.defineProperty(exports, "rateLimit", { enumerable: true, get: function () { return RateLimit_1.rateLimit; } });
37
39
  __exportStar(require("./src/Enums"), exports);
38
40
  __exportStar(require("./src/Interfaces"), exports);
@@ -17,12 +17,11 @@ class ModelTreeBuilder {
17
17
  }
18
18
  build() {
19
19
  return __awaiter(this, void 0, void 0, function* () {
20
- const logger = Services_1.LogService.getInstance();
21
20
  const tree = this.getRootLevelOfTree();
22
21
  this.createRecursiveTree(tree);
23
22
  this.addNestedRoutes(tree);
24
23
  this.version.modelTree = tree;
25
- logger.info(`[${this.version.name}] Model tree has been created.`);
24
+ Services_1.LogService.debug(`[${this.version.name}] Model tree has been created.`);
26
25
  });
27
26
  }
28
27
  getRootLevelOfTree() {
@@ -7,7 +7,7 @@ declare class RouterBuilder {
7
7
  private createRouteByModel;
8
8
  private createNestedRoutes;
9
9
  private createChildRoutes;
10
- private addExpressRoute;
10
+ private addRoute;
11
11
  private getResourcePath;
12
12
  private getRootPrefix;
13
13
  }
@@ -37,13 +37,12 @@ class RouterBuilder {
37
37
  build() {
38
38
  return __awaiter(this, void 0, void 0, function* () {
39
39
  const app = yield Services_1.IoCService.useByType("App");
40
- const logger = Services_1.LogService.getInstance();
41
40
  const generalHooks = yield new Resolvers_1.GeneralHookResolver(this.version).resolve();
42
41
  if (generalHooks.onBeforeInit) {
43
42
  generalHooks.onBeforeInit(app);
44
43
  }
45
44
  yield this.createRoutesByModelTree();
46
- logger.info(`[${this.version.name}] Express routes have been created.`);
45
+ Services_1.LogService.debug(`[${this.version.name}] All endpoints have been created.`);
47
46
  if (generalHooks.onAfterInit) {
48
47
  generalHooks.onAfterInit(app);
49
48
  }
@@ -76,8 +75,8 @@ class RouterBuilder {
76
75
  const middlewares = [
77
76
  ...model.instance.getMiddlewares(handlerType),
78
77
  ];
79
- // Adding the route to the express
80
- yield this.addExpressRoute(handlerType, url, middlewares, model, parentModel, relation);
78
+ // Adding the endpoint
79
+ yield this.addRoute(handlerType, url, middlewares, model, parentModel, relation);
81
80
  }
82
81
  yield this.createChildRoutes(model, resource, urlPrefix);
83
82
  yield this.createNestedRoutes(model, allowRecursive, urlPrefix, resource);
@@ -112,7 +111,7 @@ class RouterBuilder {
112
111
  }
113
112
  });
114
113
  }
115
- addExpressRoute(handlerType, url, middlewares, model, parentModel, relation) {
114
+ addRoute(handlerType, url, middlewares, model, parentModel, relation) {
116
115
  return __awaiter(this, void 0, void 0, function* () {
117
116
  const docs = Services_1.DocumentationService.getInstance();
118
117
  const data = {
@@ -61,13 +61,6 @@ export declare enum HttpMethods {
61
61
  GET = "GET",
62
62
  DELETE = "DELETE"
63
63
  }
64
- export declare enum LogLevels {
65
- NONE = 0,
66
- ERROR = 1,
67
- WARNING = 2,
68
- INFO = 3,
69
- ALL = 4
70
- }
71
64
  export declare enum Relationships {
72
65
  HAS_ONE = "HAS_ONE",
73
66
  HAS_MANY = "HAS_MANY"
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StatusCodes = exports.QueryFeature = exports.QueryFeatureType = exports.AxeErrorCode = exports.TimestampColumns = exports.SortTypes = exports.Relationships = exports.LogLevels = exports.HttpMethods = exports.Extensions = exports.HookFunctionTypes = exports.HandlerTypes = exports.DependencyTypes = exports.ConditionTypes = void 0;
3
+ exports.StatusCodes = exports.QueryFeature = exports.QueryFeatureType = exports.AxeErrorCode = exports.TimestampColumns = exports.SortTypes = exports.Relationships = exports.HttpMethods = exports.Extensions = exports.HookFunctionTypes = exports.HandlerTypes = exports.DependencyTypes = exports.ConditionTypes = void 0;
4
4
  var ConditionTypes;
5
5
  (function (ConditionTypes) {
6
6
  ConditionTypes["NotNull"] = "NotNull";
@@ -17,12 +17,12 @@ var ConditionTypes;
17
17
  ConditionTypes["NotIn"] = "NotIn";
18
18
  ConditionTypes["Between"] = "Between";
19
19
  ConditionTypes["NotBetween"] = "NotBetween";
20
- })(ConditionTypes = exports.ConditionTypes || (exports.ConditionTypes = {}));
20
+ })(ConditionTypes || (exports.ConditionTypes = ConditionTypes = {}));
21
21
  var DependencyTypes;
22
22
  (function (DependencyTypes) {
23
23
  DependencyTypes["BIND"] = "BIND";
24
24
  DependencyTypes["SINGLETON"] = "SINGLETON";
25
- })(DependencyTypes = exports.DependencyTypes || (exports.DependencyTypes = {}));
25
+ })(DependencyTypes || (exports.DependencyTypes = DependencyTypes = {}));
26
26
  var HandlerTypes;
27
27
  (function (HandlerTypes) {
28
28
  HandlerTypes["INSERT"] = "store";
@@ -33,7 +33,7 @@ var HandlerTypes;
33
33
  HandlerTypes["FORCE_DELETE"] = "force_delete";
34
34
  HandlerTypes["PATCH"] = "patch";
35
35
  HandlerTypes["ALL"] = "all";
36
- })(HandlerTypes = exports.HandlerTypes || (exports.HandlerTypes = {}));
36
+ })(HandlerTypes || (exports.HandlerTypes = HandlerTypes = {}));
37
37
  var HookFunctionTypes;
38
38
  (function (HookFunctionTypes) {
39
39
  HookFunctionTypes["onBeforeInsert"] = "onBeforeInsert";
@@ -56,12 +56,12 @@ var HookFunctionTypes;
56
56
  HookFunctionTypes["onAfterPaginate"] = "onAfterPaginate";
57
57
  HookFunctionTypes["onAfterAll"] = "onAfterAll";
58
58
  HookFunctionTypes["onAfterShow"] = "onAfterShow";
59
- })(HookFunctionTypes = exports.HookFunctionTypes || (exports.HookFunctionTypes = {}));
59
+ })(HookFunctionTypes || (exports.HookFunctionTypes = HookFunctionTypes = {}));
60
60
  var Extensions;
61
61
  (function (Extensions) {
62
62
  Extensions["Hooks"] = "Hooks";
63
63
  Extensions["Events"] = "Events";
64
- })(Extensions = exports.Extensions || (exports.Extensions = {}));
64
+ })(Extensions || (exports.Extensions = Extensions = {}));
65
65
  var HttpMethods;
66
66
  (function (HttpMethods) {
67
67
  HttpMethods["POST"] = "POST";
@@ -69,30 +69,22 @@ var HttpMethods;
69
69
  HttpMethods["PATCH"] = "PATCH";
70
70
  HttpMethods["GET"] = "GET";
71
71
  HttpMethods["DELETE"] = "DELETE";
72
- })(HttpMethods = exports.HttpMethods || (exports.HttpMethods = {}));
73
- var LogLevels;
74
- (function (LogLevels) {
75
- LogLevels[LogLevels["NONE"] = 0] = "NONE";
76
- LogLevels[LogLevels["ERROR"] = 1] = "ERROR";
77
- LogLevels[LogLevels["WARNING"] = 2] = "WARNING";
78
- LogLevels[LogLevels["INFO"] = 3] = "INFO";
79
- LogLevels[LogLevels["ALL"] = 4] = "ALL";
80
- })(LogLevels = exports.LogLevels || (exports.LogLevels = {}));
72
+ })(HttpMethods || (exports.HttpMethods = HttpMethods = {}));
81
73
  var Relationships;
82
74
  (function (Relationships) {
83
75
  Relationships["HAS_ONE"] = "HAS_ONE";
84
76
  Relationships["HAS_MANY"] = "HAS_MANY";
85
- })(Relationships = exports.Relationships || (exports.Relationships = {}));
77
+ })(Relationships || (exports.Relationships = Relationships = {}));
86
78
  var SortTypes;
87
79
  (function (SortTypes) {
88
80
  SortTypes["ASC"] = "ASC";
89
81
  SortTypes["DESC"] = "DESC";
90
- })(SortTypes = exports.SortTypes || (exports.SortTypes = {}));
82
+ })(SortTypes || (exports.SortTypes = SortTypes = {}));
91
83
  var TimestampColumns;
92
84
  (function (TimestampColumns) {
93
85
  TimestampColumns["CREATED_AT"] = "createdAtColumn";
94
86
  TimestampColumns["UPDATED_AT"] = "updatedAtColumn";
95
- })(TimestampColumns = exports.TimestampColumns || (exports.TimestampColumns = {}));
87
+ })(TimestampColumns || (exports.TimestampColumns = TimestampColumns = {}));
96
88
  var AxeErrorCode;
97
89
  (function (AxeErrorCode) {
98
90
  AxeErrorCode["UNACCEPTABLE_VERSION_NAME"] = "UNACCEPTABLE_VERSION_NAME";
@@ -104,12 +96,12 @@ var AxeErrorCode;
104
96
  AxeErrorCode["UNDEFINED_HOOK_MODEL_RELATION"] = "UNDEFINED_HOOK_MODEL_RELATION";
105
97
  AxeErrorCode["UNACCEPTABLE_HOOK_FILE"] = "UNACCEPTABLE_HOOK_FILE";
106
98
  AxeErrorCode["UNDEFINED_RELATION_NAME"] = "UNDEFINED_RELATION_NAME";
107
- })(AxeErrorCode = exports.AxeErrorCode || (exports.AxeErrorCode = {}));
99
+ })(AxeErrorCode || (exports.AxeErrorCode = AxeErrorCode = {}));
108
100
  var QueryFeatureType;
109
101
  (function (QueryFeatureType) {
110
102
  QueryFeatureType["Allow"] = "Allow";
111
103
  QueryFeatureType["Deny"] = "Deny";
112
- })(QueryFeatureType = exports.QueryFeatureType || (exports.QueryFeatureType = {}));
104
+ })(QueryFeatureType || (exports.QueryFeatureType = QueryFeatureType = {}));
113
105
  var QueryFeature;
114
106
  (function (QueryFeature) {
115
107
  QueryFeature["All"] = "all";
@@ -135,7 +127,7 @@ var QueryFeature;
135
127
  QueryFeature["WithAll"] = "with.*";
136
128
  QueryFeature["WithHasOne"] = "with.hasOne";
137
129
  QueryFeature["WithHasMany"] = "with.hasMany";
138
- })(QueryFeature = exports.QueryFeature || (exports.QueryFeature = {}));
130
+ })(QueryFeature || (exports.QueryFeature = QueryFeature = {}));
139
131
  var StatusCodes;
140
132
  (function (StatusCodes) {
141
133
  StatusCodes[StatusCodes["ACCEPTED"] = 202] = "ACCEPTED";
@@ -194,4 +186,4 @@ var StatusCodes;
194
186
  StatusCodes[StatusCodes["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
195
187
  StatusCodes[StatusCodes["USE_PROXY"] = 305] = "USE_PROXY";
196
188
  StatusCodes[StatusCodes["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
197
- })(StatusCodes = exports.StatusCodes || (exports.StatusCodes = {}));
189
+ })(StatusCodes || (exports.StatusCodes = StatusCodes = {}));
@@ -14,49 +14,31 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  const Services_1 = require("../Services");
16
16
  const URLService_1 = __importDefault(require("../Services/URLService"));
17
- const AxeRequest_1 = __importDefault(require("../Services/AxeRequest"));
18
- const AxeResponse_1 = __importDefault(require("../Services/AxeResponse"));
17
+ const ConverterService_1 = require("../Services/ConverterService");
19
18
  const api = Services_1.APIService.getInstance();
20
19
  const return404 = (response) => {
21
20
  response.statusCode = 404;
22
21
  response.write(JSON.stringify({ error: "Resource not found" }));
23
22
  response.end();
24
23
  };
25
- exports.default = (request, response) => __awaiter(void 0, void 0, void 0, function* () {
26
- const axeRequest = new AxeRequest_1.default(request);
27
- const match = URLService_1.default.match(axeRequest);
28
- const axeResponse = new AxeResponse_1.default(response, axeRequest.currentLanguage);
29
- if (!match) {
30
- return return404(response);
31
- }
32
- if (match.customHandler) {
33
- match.customHandler(axeRequest, axeResponse);
34
- return;
35
- }
36
- // We should set the params
37
- axeRequest.params = match.params;
38
- const database = (yield Services_1.IoCService.use("Database"));
39
- // Prepare the database by the transaction option
40
- let trx = null;
41
- if (match.hasTransaction) {
42
- trx = yield database.transaction();
43
- }
44
- const pack = Object.assign(Object.assign({}, match.data), { params: match.params, api, req: axeRequest, res: axeResponse, database: match.hasTransaction && trx ? trx : database });
45
- response.setHeader("Content-Type", "application/json");
46
- response.setHeader("x-powered-by", "Axe API");
47
- for (const phase of match.phases) {
24
+ const callPhases = (phases, pack, match, trx, axeResponse) => __awaiter(void 0, void 0, void 0, function* () {
25
+ for (const phase of phases) {
48
26
  // If there is an non-async phase, it should be an Event function
49
27
  if (phase.isAsync === false) {
28
+ Services_1.LogService.debug(`\t${phase.name}()`);
50
29
  yield phase.callback(pack);
51
30
  continue;
52
31
  }
53
32
  // Middleware and hook calls
54
33
  try {
34
+ Services_1.LogService.debug(`\t${phase.name}()`);
55
35
  yield phase.callback(pack);
56
36
  }
57
37
  catch (error) {
38
+ Services_1.LogService.error(`\t${error.message} ${phase.callback}`);
58
39
  // Rollback transaction
59
40
  if (match.hasTransaction && trx) {
41
+ Services_1.LogService.warn("\tDB transaction rollback");
60
42
  trx.rollback();
61
43
  }
62
44
  if (error.type === "ApiError") {
@@ -77,15 +59,41 @@ exports.default = (request, response) => __awaiter(void 0, void 0, void 0, funct
77
59
  // we should rollback it before the HTTP request end.
78
60
  if (pack.res.statusCode() >= 400 && pack.res.statusCode() < 599) {
79
61
  if (match.hasTransaction && trx) {
62
+ Services_1.LogService.warn("\tDB transaction rollback");
80
63
  trx.rollback();
81
64
  }
65
+ Services_1.LogService.debug(`\tResponse ${pack.res.statusCode()}`);
82
66
  break;
83
67
  }
84
68
  // If there is a valid transaction, we should commit it
85
69
  if (match.hasTransaction && trx) {
70
+ Services_1.LogService.warn("\tDB transaction commit");
86
71
  trx.commit();
87
72
  }
73
+ Services_1.LogService.debug(`\tResponse ${pack.res.statusCode()}`);
88
74
  // We should brake the for-loop
89
75
  break;
90
76
  }
91
77
  });
78
+ exports.default = (request, response) => __awaiter(void 0, void 0, void 0, function* () {
79
+ Services_1.LogService.debug(`${request.method} ${request.url}`);
80
+ const { axeRequest, axeResponse } = (0, ConverterService_1.toAxeRequestResponsePair)(request, response);
81
+ const match = URLService_1.default.match(axeRequest);
82
+ if (!match) {
83
+ Services_1.LogService.warn(`The URL is not matched! ${request.method} ${request.url}`);
84
+ return return404(response);
85
+ }
86
+ // We should set the params
87
+ axeRequest.params = match.params;
88
+ const database = (yield Services_1.IoCService.use("Database"));
89
+ // Prepare the database by the transaction option
90
+ let trx = null;
91
+ if (match.hasTransaction) {
92
+ Services_1.LogService.warn("\tDB transaction created");
93
+ trx = yield database.transaction();
94
+ }
95
+ const pack = Object.assign(Object.assign({}, match.data), { params: match.params, api, req: axeRequest, res: axeResponse, database: match.hasTransaction && trx ? trx : database });
96
+ response.setHeader("Content-Type", "application/json");
97
+ response.setHeader("x-powered-by", "Axe API");
98
+ yield callPhases(match.phases, pack, match, trx, axeResponse);
99
+ });
@@ -1,3 +1,2 @@
1
1
  import { IVersion } from "./Interfaces";
2
2
  export declare const getVersionByRequest: (urlObject: URL) => IVersion | undefined;
3
- export declare const consoleAxeError: (error: any) => void;
@@ -1,11 +1,6 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.consoleAxeError = exports.getVersionByRequest = void 0;
7
- const chalk_1 = __importDefault(require("chalk"));
8
- const change_case_1 = require("change-case");
3
+ exports.getVersionByRequest = void 0;
9
4
  const Services_1 = require("./Services");
10
5
  const getVersionByRequest = (urlObject) => {
11
6
  // Application configuration is need for the default setting.
@@ -17,50 +12,3 @@ const getVersionByRequest = (urlObject) => {
17
12
  return matchedVersion;
18
13
  };
19
14
  exports.getVersionByRequest = getVersionByRequest;
20
- const consoleAxeError = (error) => {
21
- const putWithSpace = (text, max) => {
22
- const diff = max - text.length + 3;
23
- for (let index = 0; index <= diff; index++) {
24
- text = `${text} `;
25
- }
26
- text = ` ${text}`;
27
- if (text.length > 77) {
28
- let lines = [];
29
- text = text.trim();
30
- for (let step = 0; step < text.length / 70; step++) {
31
- lines.push(text.substring(0, 70));
32
- text = text.substring(70);
33
- }
34
- lines.push(text);
35
- lines = lines.map((line) => putWithSpace(line, max));
36
- return lines.flat();
37
- }
38
- return [text];
39
- };
40
- const getMaxLength = (code, message) => {
41
- let maxLength = message.length;
42
- if (code.length > message.length) {
43
- maxLength = code.length;
44
- }
45
- if (maxLength > 70) {
46
- maxLength = 70;
47
- }
48
- return maxLength;
49
- };
50
- const maxLength = getMaxLength(error.code, error.message);
51
- const messages = [
52
- "\n",
53
- ...putWithSpace(" ", maxLength),
54
- ...putWithSpace(`[${error.code}]`, maxLength),
55
- ...putWithSpace(" ", maxLength),
56
- ...putWithSpace(error.message, maxLength),
57
- ...putWithSpace(" ", maxLength),
58
- ];
59
- console.log(chalk_1.default.bgRed.white(messages.join("\n")));
60
- console.log(chalk_1.default.cyan([
61
- "\n",
62
- "You can find more in the documentation;",
63
- `https://axe-api.com/errors.html#${(0, change_case_1.paramCase)(error.code)}`,
64
- ].join("\n")));
65
- };
66
- exports.consoleAxeError = consoleAxeError;
@@ -1,12 +1,16 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="express" />
1
3
  import { Knex } from "knex";
2
4
  import { Column } from "knex-schema-inspector/lib/types/column";
3
- import { HandlerTypes, LogLevels, HttpMethods, HookFunctionTypes, Extensions, Relationships, SortTypes, ConditionTypes, DependencyTypes, QueryFeature, QueryFeatureType } from "./Enums";
5
+ import { HandlerTypes, HttpMethods, HookFunctionTypes, Extensions, Relationships, SortTypes, ConditionTypes, DependencyTypes, QueryFeature, QueryFeatureType } from "./Enums";
4
6
  import Model from "./Model";
5
- import { PhaseFunction, SerializationFunction } from "./Types";
7
+ import { AdaptorTypes, HandlerFunction, HookFunctions, MiddlewareFunction, PhaseFunction, SerializationFunction } from "./Types";
6
8
  import { ModelListService, QueryService } from "./Services";
7
9
  import AxeRequest from "./Services/AxeRequest";
8
10
  import AxeResponse from "./Services/AxeResponse";
9
11
  import App from "./Services/App";
12
+ import { LoggerOptions } from "pino";
13
+ import { IncomingMessage } from "http";
10
14
  export interface IColumn extends Column {
11
15
  table_name: string;
12
16
  }
@@ -34,6 +38,26 @@ export interface IQueryConfig {
34
38
  limits: Array<IQueryLimitConfig[]>;
35
39
  defaults?: IQueryDefaultConfig;
36
40
  }
41
+ export interface IRedisOptions {
42
+ host?: string;
43
+ port?: number;
44
+ password?: string;
45
+ db?: number;
46
+ }
47
+ export interface IRateLimitAdaptorConfig {
48
+ type: AdaptorTypes;
49
+ redis?: IRedisOptions;
50
+ }
51
+ export interface IRateLimitOptions {
52
+ maxRequests: number;
53
+ windowInSeconds: number;
54
+ }
55
+ export interface IRateLimitConfig extends IRateLimitOptions {
56
+ enabled: boolean;
57
+ adaptor: IRateLimitAdaptorConfig;
58
+ trustProxyIP: boolean;
59
+ keyGenerator?: (req: IncomingMessage) => string;
60
+ }
37
61
  export interface IVersionConfig {
38
62
  transaction: boolean | IHandlerBasedTransactionConfig | IHandlerBasedTransactionConfig[];
39
63
  serializers: ((data: any, request: AxeRequest) => void)[] | IHandlerBasedSerializer[];
@@ -44,9 +68,10 @@ export interface IVersionConfig {
44
68
  export interface IApplicationConfig extends IConfig {
45
69
  env: string;
46
70
  port: number;
47
- logLevel: LogLevels;
48
71
  prefix: string;
49
72
  database: IDatabaseConfig;
73
+ pino: LoggerOptions;
74
+ rateLimit: IRateLimitConfig;
50
75
  }
51
76
  export interface ILanguage {
52
77
  title: string;
@@ -86,7 +111,7 @@ export interface IGeneralHooks {
86
111
  }
87
112
  export interface IHandlerBaseMiddleware {
88
113
  handler: HandlerTypes[];
89
- middleware: (context: IRequestPack) => Promise<void> | void;
114
+ middleware: PhaseFunction;
90
115
  }
91
116
  export interface IMethodBaseConfig {
92
117
  [HttpMethods.POST]?: string[];
@@ -103,8 +128,8 @@ export interface IModelService {
103
128
  relations: IRelation[];
104
129
  columns: IColumn[];
105
130
  columnNames: string[];
106
- hooks: Record<HookFunctionTypes, PhaseFunction>;
107
- events: Record<HookFunctionTypes, PhaseFunction>;
131
+ hooks: HookFunctions;
132
+ events: HookFunctions;
108
133
  isRecursive: boolean;
109
134
  children: IModelService[];
110
135
  queryLimits: IQueryLimitConfig[];
@@ -200,7 +225,16 @@ export interface IDependency {
200
225
  instance: any;
201
226
  }
202
227
  export interface IPhaseDefinition {
228
+ name: string;
203
229
  isAsync: boolean;
204
230
  callback: PhaseFunction;
205
231
  }
232
+ export interface AxeRequestResponsePair {
233
+ axeRequest: AxeRequest;
234
+ axeResponse: AxeResponse;
235
+ }
236
+ export interface MiddlewareResolution {
237
+ middlewares: MiddlewareFunction[];
238
+ handler: HandlerFunction;
239
+ }
206
240
  export {};
@@ -0,0 +1,6 @@
1
+ import { AdaptorTypes } from "../../Types";
2
+ import RedisAdaptor from "./RedisAdaptor";
3
+ import MemoryAdaptor from "./MemoryAdaptor";
4
+ import { IRedisOptions } from "src/Interfaces";
5
+ declare const _default: (adaptor: AdaptorTypes, redisOptions: IRedisOptions | undefined, prefix: string) => RedisAdaptor | MemoryAdaptor;
6
+ export default _default;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const RedisAdaptor_1 = __importDefault(require("./RedisAdaptor"));
7
+ const MemoryAdaptor_1 = __importDefault(require("./MemoryAdaptor"));
8
+ exports.default = (adaptor, redisOptions, prefix) => {
9
+ switch (adaptor) {
10
+ case "redis":
11
+ return new RedisAdaptor_1.default(redisOptions, prefix);
12
+ case "memory":
13
+ return new MemoryAdaptor_1.default(prefix);
14
+ default:
15
+ throw new Error(`Adaptor type is not found: ${adaptor}`);
16
+ }
17
+ };
@@ -0,0 +1,6 @@
1
+ interface IAdaptor {
2
+ get(key: string): Promise<string | null>;
3
+ set(key: string, value: string, ttl: number): Promise<void>;
4
+ decr(key: string, ttl: number): Promise<void>;
5
+ }
6
+ export default IAdaptor;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,10 @@
1
+ import IAdaptor from "./IAdaptor";
2
+ declare class MemoryAdaptor implements IAdaptor {
3
+ private client;
4
+ private prefix;
5
+ constructor(prefix: string);
6
+ get(key: string): Promise<string | null>;
7
+ set(key: string, value: string, ttl: number): Promise<void>;
8
+ decr(key: string, ttl: number): Promise<void>;
9
+ }
10
+ export default MemoryAdaptor;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const node_cache_1 = __importDefault(require("node-cache"));
16
+ class MemoryAdaptor {
17
+ constructor(prefix) {
18
+ this.client = new node_cache_1.default();
19
+ this.prefix = prefix;
20
+ }
21
+ get(key) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ return this.client.get(`${this.prefix}${key}`) || null;
24
+ });
25
+ }
26
+ set(key, value, ttl) {
27
+ return __awaiter(this, void 0, void 0, function* () {
28
+ this.client.set(`${this.prefix}${key}`, value, ttl);
29
+ });
30
+ }
31
+ decr(key, ttl) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ const value = yield this.get(key);
34
+ if (value) {
35
+ const newValue = parseInt(value) - 1;
36
+ this.set(key, newValue.toString(), ttl);
37
+ }
38
+ });
39
+ }
40
+ }
41
+ exports.default = MemoryAdaptor;
@@ -0,0 +1,11 @@
1
+ import IAdaptor from "./IAdaptor";
2
+ import { IRedisOptions } from "../../Interfaces";
3
+ declare class RedisAdaptor implements IAdaptor {
4
+ private client;
5
+ private prefix;
6
+ constructor(options: IRedisOptions | undefined, prefix: string);
7
+ get(key: string): Promise<string | null>;
8
+ set(key: string, value: string, ttl: number): Promise<void>;
9
+ decr(key: string): Promise<void>;
10
+ }
11
+ export default RedisAdaptor;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const redis_1 = require("redis");
13
+ class RedisAdaptor {
14
+ constructor(options, prefix) {
15
+ this.client = (0, redis_1.createClient)(options);
16
+ this.prefix = prefix;
17
+ this.client.connect();
18
+ }
19
+ get(key) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ return yield this.client.get(`${this.prefix}${key}`);
22
+ });
23
+ }
24
+ set(key, value, ttl) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ yield this.client.setEx(`${this.prefix}${key}`, ttl, value);
27
+ });
28
+ }
29
+ decr(key) {
30
+ return __awaiter(this, void 0, void 0, function* () {
31
+ yield this.client.decr(`${this.prefix}${key}`);
32
+ });
33
+ }
34
+ }
35
+ exports.default = RedisAdaptor;
@@ -0,0 +1,6 @@
1
+ import { IncomingMessage, ServerResponse } from "http";
2
+ import { IApplicationConfig, IRateLimitOptions, IRequestPack } from "../../Interfaces";
3
+ export declare const setupRateLimitAdaptors: (config: IApplicationConfig) => void;
4
+ export declare const rateLimit: (options?: IRateLimitOptions) => (context: IRequestPack) => Promise<void>;
5
+ declare const _default: (req: IncomingMessage, res: ServerResponse, next: any) => Promise<any>;
6
+ export default _default;