axe-api 1.0.0-rc1 → 1.0.0-rc10

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 (58) 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 +41 -31
  9. package/build/src/Helpers.d.ts +0 -1
  10. package/build/src/Helpers.js +1 -53
  11. package/build/src/Interfaces.d.ts +48 -10
  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/Model.d.ts +4 -4
  23. package/build/src/Phases/Delete/QueryPhase.js +3 -1
  24. package/build/src/Phases/ForceDelete/PreparePhase.js +3 -1
  25. package/build/src/Phases/ForceDelete/QueryPhase.js +3 -1
  26. package/build/src/Phases/Paginate/FetchPhase.js +11 -0
  27. package/build/src/Phases/Paginate/PreparePhase.js +0 -8
  28. package/build/src/Phases/Patch/PrepareActionPhase.js +1 -1
  29. package/build/src/Phases/Show/FetchPhase.js +14 -2
  30. package/build/src/Phases/Show/PreparePhase.js +0 -9
  31. package/build/src/Phases/Single/GetPhase.js +3 -1
  32. package/build/src/Phases/Store/PreparePhase.js +1 -1
  33. package/build/src/Phases/Update/PrepareActionPhase.js +1 -1
  34. package/build/src/Resolvers/ModelResolver.js +9 -4
  35. package/build/src/Resolvers/VersionConfigResolver.js +6 -1
  36. package/build/src/Resolvers/VersionResolver.js +1 -2
  37. package/build/src/Server.js +18 -10
  38. package/build/src/Services/APIService.d.ts +3 -3
  39. package/build/src/Services/APIService.js +3 -8
  40. package/build/src/Services/App.d.ts +6 -6
  41. package/build/src/Services/App.js +53 -10
  42. package/build/src/Services/AxeRequest.d.ts +2 -0
  43. package/build/src/Services/AxeRequest.js +26 -0
  44. package/build/src/Services/AxeResponse.d.ts +3 -2
  45. package/build/src/Services/AxeResponse.js +7 -4
  46. package/build/src/Services/ConverterService.d.ts +9 -0
  47. package/build/src/Services/ConverterService.js +49 -0
  48. package/build/src/Services/LogService.d.ts +8 -12
  49. package/build/src/Services/LogService.js +16 -33
  50. package/build/src/Services/ModelService.d.ts +3 -3
  51. package/build/src/Services/QueryService.d.ts +3 -3
  52. package/build/src/Services/SchemaValidatorService.js +1 -2
  53. package/build/src/Services/URLService.d.ts +3 -3
  54. package/build/src/Services/URLService.js +36 -8
  55. package/build/src/Types.d.ts +16 -5
  56. package/build/src/constants.d.ts +4 -13
  57. package/build/src/constants.js +98 -72
  58. package/package.json +24 -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,76 +14,86 @@ 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, context, 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) {
50
- yield phase.callback(pack);
28
+ Services_1.LogService.debug(`\t${phase.name}()`);
29
+ yield phase.callback(context);
51
30
  continue;
52
31
  }
53
32
  // Middleware and hook calls
54
33
  try {
55
- yield phase.callback(pack);
34
+ Services_1.LogService.debug(`\t${phase.name}()`);
35
+ yield phase.callback(context);
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") {
63
45
  const apiError = error;
64
- return axeResponse.json({ error: apiError.message }, apiError.status);
46
+ return axeResponse
47
+ .status(apiError.status)
48
+ .json({ error: apiError.message });
65
49
  }
66
50
  // TODO: We need an error handler.
67
- axeResponse.json({ error: error.toString() }, 500);
51
+ axeResponse.status(500).json({ error: error.toString() });
68
52
  break;
69
53
  }
70
54
  // If the response is not created, we should go to the next phase
71
- if (pack.res.isResponded() === false) {
55
+ if (context.res.isResponded() === false) {
72
56
  continue;
73
57
  }
74
58
  // If the response is an error, and we have an active transaction,
75
59
  // we should rollback it before the HTTP request end.
76
- if (pack.res.statusCode() >= 400 && pack.res.statusCode() < 599) {
60
+ if (context.res.statusCode() >= 400 && context.res.statusCode() < 599) {
77
61
  if (match.hasTransaction && trx) {
62
+ Services_1.LogService.warn("\tDB transaction rollback");
78
63
  trx.rollback();
79
64
  }
65
+ Services_1.LogService.debug(`\tResponse ${context.res.statusCode()}`);
80
66
  break;
81
67
  }
82
68
  // If there is a valid transaction, we should commit it
83
69
  if (match.hasTransaction && trx) {
70
+ Services_1.LogService.warn("\tDB transaction commit");
84
71
  trx.commit();
85
72
  }
73
+ Services_1.LogService.debug(`\tResponse ${context.res.statusCode()}`);
86
74
  // We should brake the for-loop
87
75
  break;
88
76
  }
89
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 context = 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, context, 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,17 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="express" />
1
3
  import { Knex } from "knex";
4
+ import { Options as FormOptions } from "formidable";
2
5
  import { Column } from "knex-schema-inspector/lib/types/column";
3
- import { HandlerTypes, LogLevels, HttpMethods, HookFunctionTypes, Extensions, Relationships, SortTypes, ConditionTypes, DependencyTypes, QueryFeature, QueryFeatureType } from "./Enums";
6
+ import { HandlerTypes, HttpMethods, HookFunctionTypes, Extensions, Relationships, SortTypes, ConditionTypes, DependencyTypes, QueryFeature, QueryFeatureType } from "./Enums";
4
7
  import Model from "./Model";
5
- import { PhaseFunction, SerializationFunction } from "./Types";
8
+ import { AdaptorTypes, HandlerFunction, HookFunctions, MiddlewareFunction, StepTypes, PhaseFunction, SerializationFunction } from "./Types";
6
9
  import { ModelListService, QueryService } from "./Services";
7
10
  import AxeRequest from "./Services/AxeRequest";
8
11
  import AxeResponse from "./Services/AxeResponse";
9
12
  import App from "./Services/App";
13
+ import { LoggerOptions } from "pino";
14
+ import { IncomingMessage } from "http";
10
15
  export interface IColumn extends Column {
11
16
  table_name: string;
12
17
  }
@@ -34,20 +39,44 @@ export interface IQueryConfig {
34
39
  limits: Array<IQueryLimitConfig[]>;
35
40
  defaults?: IQueryDefaultConfig;
36
41
  }
37
- export interface IVersionConfig {
42
+ export interface IRedisOptions {
43
+ host?: string;
44
+ port?: number;
45
+ password?: string;
46
+ db?: number;
47
+ }
48
+ export interface IRateLimitAdaptorConfig {
49
+ type: AdaptorTypes;
50
+ redis?: IRedisOptions;
51
+ }
52
+ export interface IRateLimitOptions {
53
+ maxRequests: number;
54
+ windowInSeconds: number;
55
+ }
56
+ export interface IRateLimitConfig extends IRateLimitOptions {
57
+ enabled: boolean;
58
+ adaptor: IRateLimitAdaptorConfig;
59
+ trustProxyIP: boolean;
60
+ keyGenerator?: (req: IncomingMessage) => string;
61
+ }
62
+ export interface AxeVersionConfig {
38
63
  transaction: boolean | IHandlerBasedTransactionConfig | IHandlerBasedTransactionConfig[];
39
64
  serializers: ((data: any, request: AxeRequest) => void)[] | IHandlerBasedSerializer[];
40
65
  supportedLanguages: string[];
41
66
  defaultLanguage: string;
42
67
  query: IQueryConfig;
68
+ formidable: FormOptions;
43
69
  }
44
- export interface IApplicationConfig extends IConfig {
70
+ export type IVersionConfig = Partial<AxeVersionConfig>;
71
+ export interface AxeConfig extends IConfig {
45
72
  env: string;
46
73
  port: number;
47
- logLevel: LogLevels;
48
74
  prefix: string;
49
75
  database: IDatabaseConfig;
76
+ pino: LoggerOptions;
77
+ rateLimit: IRateLimitConfig;
50
78
  }
79
+ export type IApplicationConfig = Partial<AxeConfig>;
51
80
  export interface ILanguage {
52
81
  title: string;
53
82
  language: string;
@@ -69,7 +98,7 @@ export interface IVersionFolder {
69
98
  }
70
99
  export interface IVersion {
71
100
  name: string;
72
- config: IVersionConfig;
101
+ config: AxeVersionConfig;
73
102
  folders: IVersionFolder;
74
103
  modelList: ModelListService;
75
104
  modelTree: IModelService[];
@@ -78,7 +107,7 @@ export interface IAPI {
78
107
  rootFolder: string;
79
108
  appFolder: string;
80
109
  versions: IVersion[];
81
- config: IApplicationConfig;
110
+ config: AxeConfig;
82
111
  }
83
112
  export interface IGeneralHooks {
84
113
  onBeforeInit: (app: App) => void | null;
@@ -86,7 +115,7 @@ export interface IGeneralHooks {
86
115
  }
87
116
  export interface IHandlerBaseMiddleware {
88
117
  handler: HandlerTypes[];
89
- middleware: (context: IRequestPack) => Promise<void>;
118
+ middleware: StepTypes;
90
119
  }
91
120
  export interface IMethodBaseConfig {
92
121
  [HttpMethods.POST]?: string[];
@@ -103,8 +132,8 @@ export interface IModelService {
103
132
  relations: IRelation[];
104
133
  columns: IColumn[];
105
134
  columnNames: string[];
106
- hooks: Record<HookFunctionTypes, PhaseFunction>;
107
- events: Record<HookFunctionTypes, PhaseFunction>;
135
+ hooks: HookFunctions;
136
+ events: HookFunctions;
108
137
  isRecursive: boolean;
109
138
  children: IModelService[];
110
139
  queryLimits: IQueryLimitConfig[];
@@ -200,7 +229,16 @@ export interface IDependency {
200
229
  instance: any;
201
230
  }
202
231
  export interface IPhaseDefinition {
232
+ name: string;
203
233
  isAsync: boolean;
204
234
  callback: PhaseFunction;
205
235
  }
236
+ export interface AxeRequestResponsePair {
237
+ axeRequest: AxeRequest;
238
+ axeResponse: AxeResponse;
239
+ }
240
+ export interface MiddlewareResolution {
241
+ middlewares: (MiddlewareFunction | HandlerFunction)[];
242
+ handler: HandlerFunction;
243
+ }
206
244
  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;