axe-api 0.31.4 → 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 (150) hide show
  1. package/build/dev-kit.d.ts +1 -0
  2. package/build/dev-kit.js +16 -0
  3. package/build/index.d.ts +3 -2
  4. package/build/index.js +6 -1
  5. package/build/src/Builders/ModelTreeBuilder.js +1 -2
  6. package/build/src/Builders/RouterBuilder.d.ts +1 -5
  7. package/build/src/Builders/RouterBuilder.js +17 -112
  8. package/build/src/Enums.d.ts +0 -7
  9. package/build/src/Enums.js +14 -22
  10. package/build/src/Handlers/DocsHTMLHandler.d.ts +3 -2
  11. package/build/src/Handlers/Helpers.d.ts +7 -7
  12. package/build/src/Handlers/MetadataHandler.d.ts +3 -2
  13. package/build/src/Handlers/RequestHandler.d.ts +3 -0
  14. package/build/src/Handlers/RequestHandler.js +99 -0
  15. package/build/src/Handlers/RoutesHandler.d.ts +3 -2
  16. package/build/src/Helpers.d.ts +1 -3
  17. package/build/src/Helpers.js +4 -68
  18. package/build/src/Interfaces.d.ts +74 -35
  19. package/build/src/Middlewares/RateLimit/AdaptorFactory.d.ts +6 -0
  20. package/build/src/Middlewares/RateLimit/AdaptorFactory.js +17 -0
  21. package/build/src/Middlewares/RateLimit/IAdaptor.d.ts +6 -0
  22. package/build/src/Middlewares/RateLimit/IAdaptor.js +2 -0
  23. package/build/src/Middlewares/RateLimit/MemoryAdaptor.d.ts +10 -0
  24. package/build/src/Middlewares/RateLimit/MemoryAdaptor.js +41 -0
  25. package/build/src/Middlewares/RateLimit/RedisAdaptor.d.ts +11 -0
  26. package/build/src/Middlewares/RateLimit/RedisAdaptor.js +35 -0
  27. package/build/src/Middlewares/RateLimit/index.d.ts +6 -0
  28. package/build/src/Middlewares/RateLimit/index.js +118 -0
  29. package/build/src/Model.d.ts +4 -4
  30. package/build/src/Phases/All/FetchPhase.d.ts +3 -0
  31. package/build/src/{Middlewares/acceptLanguageMiddleware.js → Phases/All/FetchPhase.js} +4 -10
  32. package/build/src/Phases/All/PreparePhase.d.ts +3 -0
  33. package/build/src/Phases/All/PreparePhase.js +30 -0
  34. package/build/src/Phases/All/index.d.ts +4 -0
  35. package/build/src/{Middlewares → Phases/All}/index.js +4 -3
  36. package/build/src/Phases/Delete/ActionPhase.d.ts +3 -0
  37. package/build/src/Phases/Delete/ActionPhase.js +24 -0
  38. package/build/src/Phases/Delete/PreparePhase.d.ts +3 -0
  39. package/build/src/Phases/Delete/PreparePhase.js +25 -0
  40. package/build/src/Phases/Delete/QueryPhase.d.ts +3 -0
  41. package/build/src/Phases/Delete/QueryPhase.js +22 -0
  42. package/build/src/Phases/Delete/ResponsePhase.d.ts +3 -0
  43. package/build/src/Phases/Delete/ResponsePhase.js +14 -0
  44. package/build/src/Phases/Delete/index.d.ts +7 -0
  45. package/build/src/Phases/Delete/index.js +15 -0
  46. package/build/src/Phases/ForceDelete/ActionPhase.d.ts +3 -0
  47. package/build/src/Phases/ForceDelete/ActionPhase.js +16 -0
  48. package/build/src/Phases/ForceDelete/PreparePhase.d.ts +3 -0
  49. package/build/src/Phases/ForceDelete/PreparePhase.js +30 -0
  50. package/build/src/Phases/ForceDelete/QueryPhase.d.ts +3 -0
  51. package/build/src/Phases/ForceDelete/QueryPhase.js +22 -0
  52. package/build/src/Phases/ForceDelete/index.d.ts +6 -0
  53. package/build/src/Phases/ForceDelete/index.js +13 -0
  54. package/build/src/Phases/List/RelationalPhase.d.ts +3 -0
  55. package/build/src/Phases/List/RelationalPhase.js +17 -0
  56. package/build/src/Phases/List/ResultPhase.d.ts +3 -0
  57. package/build/src/Phases/List/ResultPhase.js +14 -0
  58. package/build/src/Phases/List/SerializePhase.d.ts +3 -0
  59. package/build/src/Phases/List/SerializePhase.js +19 -0
  60. package/build/src/Phases/List/index.d.ts +6 -0
  61. package/build/src/Phases/List/index.js +13 -0
  62. package/build/src/Phases/Paginate/FetchPhase.d.ts +3 -0
  63. package/build/src/Phases/Paginate/FetchPhase.js +30 -0
  64. package/build/src/Phases/Paginate/PreparePhase.d.ts +3 -0
  65. package/build/src/Phases/Paginate/PreparePhase.js +22 -0
  66. package/build/src/Phases/Paginate/index.d.ts +5 -0
  67. package/build/src/Phases/Paginate/index.js +11 -0
  68. package/build/src/Phases/Patch/PrepareActionPhase.d.ts +3 -0
  69. package/build/src/Phases/Patch/PrepareActionPhase.js +37 -0
  70. package/build/src/Phases/Patch/index.d.ts +4 -0
  71. package/build/src/Phases/Patch/index.js +9 -0
  72. package/build/src/Phases/Show/FetchPhase.d.ts +3 -0
  73. package/build/src/Phases/Show/FetchPhase.js +35 -0
  74. package/build/src/Phases/Show/PreparePhase.d.ts +3 -0
  75. package/build/src/Phases/Show/PreparePhase.js +22 -0
  76. package/build/src/Phases/Show/index.d.ts +5 -0
  77. package/build/src/Phases/Show/index.js +11 -0
  78. package/build/src/Phases/Single/GetPhase.d.ts +3 -0
  79. package/build/src/Phases/Single/GetPhase.js +29 -0
  80. package/build/src/Phases/Single/PrepareGetPhase.d.ts +3 -0
  81. package/build/src/Phases/Single/PrepareGetPhase.js +19 -0
  82. package/build/src/Phases/Single/RelationalPhase.d.ts +3 -0
  83. package/build/src/Phases/Single/RelationalPhase.js +17 -0
  84. package/build/src/Phases/Single/ResultPhase.d.ts +3 -0
  85. package/build/src/Phases/Single/ResultPhase.js +14 -0
  86. package/build/src/Phases/Single/SerializePhase.d.ts +3 -0
  87. package/build/src/Phases/Single/SerializePhase.js +18 -0
  88. package/build/src/Phases/Single/index.d.ts +8 -0
  89. package/build/src/Phases/Single/index.js +17 -0
  90. package/build/src/Phases/Store/ActionPhase.d.ts +3 -0
  91. package/build/src/Phases/Store/ActionPhase.js +29 -0
  92. package/build/src/Phases/Store/PreparePhase.d.ts +3 -0
  93. package/build/src/Phases/Store/PreparePhase.js +46 -0
  94. package/build/src/Phases/Store/index.d.ts +5 -0
  95. package/build/src/Phases/Store/index.js +11 -0
  96. package/build/src/Phases/Update/ActionPhase.d.ts +3 -0
  97. package/build/src/Phases/Update/ActionPhase.js +22 -0
  98. package/build/src/Phases/Update/PrepareActionPhase.d.ts +3 -0
  99. package/build/src/Phases/Update/PrepareActionPhase.js +37 -0
  100. package/build/src/Phases/Update/index.d.ts +5 -0
  101. package/build/src/Phases/Update/index.js +11 -0
  102. package/build/src/Resolvers/ModelResolver.js +9 -4
  103. package/build/src/Resolvers/VersionConfigResolver.js +6 -1
  104. package/build/src/Resolvers/VersionResolver.js +1 -2
  105. package/build/src/Server.d.ts +0 -1
  106. package/build/src/Server.js +29 -24
  107. package/build/src/Services/APIService.d.ts +3 -3
  108. package/build/src/Services/APIService.js +3 -8
  109. package/build/src/Services/App.d.ts +14 -0
  110. package/build/src/Services/App.js +80 -0
  111. package/build/src/Services/AxeRequest.d.ts +26 -0
  112. package/build/src/Services/AxeRequest.js +85 -0
  113. package/build/src/Services/AxeResponse.d.ts +18 -0
  114. package/build/src/Services/AxeResponse.js +41 -0
  115. package/build/src/Services/ConverterService.d.ts +9 -0
  116. package/build/src/Services/ConverterService.js +49 -0
  117. package/build/src/Services/LogService.d.ts +8 -12
  118. package/build/src/Services/LogService.js +16 -34
  119. package/build/src/Services/ModelService.d.ts +4 -4
  120. package/build/src/Services/QueryService.d.ts +4 -4
  121. package/build/src/Services/QueryService.js +14 -11
  122. package/build/src/Services/SchemaValidatorService.js +1 -2
  123. package/build/src/Services/URLService.d.ts +29 -0
  124. package/build/src/Services/URLService.js +144 -0
  125. package/build/src/Services/index.d.ts +4 -1
  126. package/build/src/Services/index.js +7 -1
  127. package/build/src/Types.d.ts +18 -6
  128. package/build/src/constants.d.ts +12 -14
  129. package/build/src/constants.js +200 -13
  130. package/package.json +29 -20
  131. package/build/src/Handlers/AllHandler.d.ts +0 -3
  132. package/build/src/Handlers/AllHandler.js +0 -45
  133. package/build/src/Handlers/DestroyHandler.d.ts +0 -3
  134. package/build/src/Handlers/DestroyHandler.js +0 -51
  135. package/build/src/Handlers/ForceDestroyHandler.d.ts +0 -3
  136. package/build/src/Handlers/ForceDestroyHandler.js +0 -45
  137. package/build/src/Handlers/HandlerFactory.d.ts +0 -6
  138. package/build/src/Handlers/HandlerFactory.js +0 -39
  139. package/build/src/Handlers/PaginateHandler.d.ts +0 -3
  140. package/build/src/Handlers/PaginateHandler.js +0 -49
  141. package/build/src/Handlers/PatchHandler.d.ts +0 -3
  142. package/build/src/Handlers/PatchHandler.js +0 -69
  143. package/build/src/Handlers/ShowHandler.d.ts +0 -3
  144. package/build/src/Handlers/ShowHandler.js +0 -55
  145. package/build/src/Handlers/StoreHandler.d.ts +0 -3
  146. package/build/src/Handlers/StoreHandler.js +0 -65
  147. package/build/src/Handlers/UpdateHandler.d.ts +0 -3
  148. package/build/src/Handlers/UpdateHandler.js +0 -69
  149. package/build/src/Middlewares/acceptLanguageMiddleware.d.ts +0 -3
  150. package/build/src/Middlewares/index.d.ts +0 -2
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
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 node_color_log_1 = __importDefault(require("node-color-log"));
7
+ const dotenv_1 = __importDefault(require("dotenv"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const index_1 = require("./index");
10
+ node_color_log_1.default.bgColor("yellow").color("black").log("Axe API dev-kit (1.0.1)");
11
+ node_color_log_1.default
12
+ .color("blue")
13
+ .log("Docs: https://axe-api.com/contribution/fundamentals.html \n");
14
+ dotenv_1.default.config();
15
+ const server = new index_1.Server();
16
+ server.start(path_1.default.join(__dirname, "dev-kit"));
package/build/index.d.ts CHANGED
@@ -2,7 +2,8 @@ import Server from "./src/Server";
2
2
  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
- import { IoCService, allow, deny } from "./src/Services";
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 { 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 = 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"));
@@ -31,5 +31,10 @@ const Services_1 = require("./src/Services");
31
31
  Object.defineProperty(exports, "IoCService", { enumerable: true, get: function () { return Services_1.IoCService; } });
32
32
  Object.defineProperty(exports, "allow", { enumerable: true, get: function () { return Services_1.allow; } });
33
33
  Object.defineProperty(exports, "deny", { enumerable: true, get: function () { return Services_1.deny; } });
34
+ Object.defineProperty(exports, "App", { enumerable: true, get: function () { return Services_1.App; } });
35
+ Object.defineProperty(exports, "AxeRequest", { enumerable: true, get: function () { return Services_1.AxeRequest; } });
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; } });
34
39
  __exportStar(require("./src/Enums"), exports);
35
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,11 +7,7 @@ declare class RouterBuilder {
7
7
  private createRouteByModel;
8
8
  private createNestedRoutes;
9
9
  private createChildRoutes;
10
- private getPrimaryKeyName;
11
- private ucFirst;
12
- private addExpressRoute;
13
- private requestHandler;
14
- private sendErrorAsResponse;
10
+ private addRoute;
15
11
  private getResourcePath;
16
12
  private getRootPrefix;
17
13
  }
@@ -17,21 +17,13 @@ const change_case_1 = require("change-case");
17
17
  const Resolvers_1 = require("../Resolvers");
18
18
  const constants_1 = require("../constants");
19
19
  const Enums_1 = require("../Enums");
20
- const HandlerFactory_1 = __importDefault(require("../Handlers/HandlerFactory"));
21
20
  const Services_1 = require("../Services");
22
- const Middlewares_1 = require("../Middlewares");
21
+ const URLService_1 = __importDefault(require("../Services/URLService"));
23
22
  class RouterBuilder {
24
23
  constructor(version) {
25
- this.getPrimaryKeyName = (model) => {
26
- return (pluralize_1.default.singular(model.name).toLowerCase() +
27
- this.ucFirst(model.instance.primaryKey));
28
- };
29
- this.ucFirst = (value) => {
30
- return value.charAt(0).toUpperCase() + value.slice(1);
31
- };
32
24
  this.getRootPrefix = () => __awaiter(this, void 0, void 0, function* () {
33
25
  const api = Services_1.APIService.getInstance();
34
- let prefix = api.config.prefix || "api";
26
+ let prefix = api.config.prefix;
35
27
  if (prefix.startsWith("/")) {
36
28
  prefix = prefix.substring(1);
37
29
  }
@@ -45,13 +37,12 @@ class RouterBuilder {
45
37
  build() {
46
38
  return __awaiter(this, void 0, void 0, function* () {
47
39
  const app = yield Services_1.IoCService.useByType("App");
48
- const logger = Services_1.LogService.getInstance();
49
40
  const generalHooks = yield new Resolvers_1.GeneralHookResolver(this.version).resolve();
50
41
  if (generalHooks.onBeforeInit) {
51
42
  generalHooks.onBeforeInit(app);
52
43
  }
53
44
  yield this.createRoutesByModelTree();
54
- logger.info(`[${this.version.name}] Express routes have been created.`);
45
+ Services_1.LogService.debug(`[${this.version.name}] All endpoints have been created.`);
55
46
  if (generalHooks.onAfterInit) {
56
47
  generalHooks.onAfterInit(app);
57
48
  }
@@ -82,11 +73,10 @@ class RouterBuilder {
82
73
  // internal middlewares such as `Accept Language Middleware` which parse
83
74
  // the "accept-language" header to use in the application general.
84
75
  const middlewares = [
85
- Middlewares_1.acceptLanguageMiddleware,
86
76
  ...model.instance.getMiddlewares(handlerType),
87
77
  ];
88
- // Adding the route to the express
89
- yield this.addExpressRoute(handlerType, url, middlewares, model, parentModel, relation);
78
+ // Adding the endpoint
79
+ yield this.addRoute(handlerType, url, middlewares, model, parentModel, relation);
90
80
  }
91
81
  yield this.createChildRoutes(model, resource, urlPrefix);
92
82
  yield this.createNestedRoutes(model, allowRecursive, urlPrefix, resource);
@@ -121,107 +111,22 @@ class RouterBuilder {
121
111
  }
122
112
  });
123
113
  }
124
- addExpressRoute(handlerType, url, middlewares, model, parentModel, relation) {
114
+ addRoute(handlerType, url, middlewares, model, parentModel, relation) {
125
115
  return __awaiter(this, void 0, void 0, function* () {
126
116
  const docs = Services_1.DocumentationService.getInstance();
127
- const app = yield Services_1.IoCService.useByType("App");
128
- const handler = (req, res, next) => __awaiter(this, void 0, void 0, function* () {
129
- try {
130
- yield this.requestHandler(handlerType, req, res, model, parentModel, relation);
131
- }
132
- catch (error) {
133
- // Catch error then pass it to the express error handler
134
- next(error);
135
- }
136
- });
137
- switch (handlerType) {
138
- case Enums_1.HandlerTypes.ALL:
139
- app.get(url, middlewares, handler);
140
- docs.push(this.version, Enums_1.HandlerTypes.ALL, Enums_1.HttpMethods.GET, url, model);
141
- break;
142
- case Enums_1.HandlerTypes.DELETE:
143
- app.delete(url, middlewares, handler);
144
- docs.push(this.version, Enums_1.HandlerTypes.DELETE, Enums_1.HttpMethods.DELETE, url, model);
145
- break;
146
- case Enums_1.HandlerTypes.FORCE_DELETE:
147
- app.delete(url, middlewares, handler);
148
- docs.push(this.version, Enums_1.HandlerTypes.FORCE_DELETE, Enums_1.HttpMethods.DELETE, url, model);
149
- break;
150
- case Enums_1.HandlerTypes.INSERT:
151
- app.post(url, middlewares, handler);
152
- docs.push(this.version, Enums_1.HandlerTypes.INSERT, Enums_1.HttpMethods.POST, url, model);
153
- break;
154
- case Enums_1.HandlerTypes.PAGINATE:
155
- app.get(url, middlewares, handler);
156
- docs.push(this.version, Enums_1.HandlerTypes.PAGINATE, Enums_1.HttpMethods.GET, url, model);
157
- break;
158
- case Enums_1.HandlerTypes.PATCH:
159
- app.patch(url, middlewares, handler);
160
- docs.push(this.version, Enums_1.HandlerTypes.PATCH, Enums_1.HttpMethods.PATCH, url, model);
161
- break;
162
- case Enums_1.HandlerTypes.SHOW:
163
- app.get(url, middlewares, handler);
164
- docs.push(this.version, Enums_1.HandlerTypes.SHOW, Enums_1.HttpMethods.GET, url, model);
165
- break;
166
- case Enums_1.HandlerTypes.UPDATE:
167
- app.put(url, middlewares, handler);
168
- docs.push(this.version, Enums_1.HandlerTypes.UPDATE, Enums_1.HttpMethods.PUT, url, model);
169
- break;
170
- default:
171
- throw new Error("Undefined handler type");
172
- }
117
+ const data = {
118
+ version: this.version,
119
+ handlerType,
120
+ model,
121
+ parentModel,
122
+ relation,
123
+ };
124
+ // Adding the route
125
+ yield URLService_1.default.add(constants_1.HANDLER_METHOD_MAP[handlerType], url, data, middlewares);
126
+ // Documentation
127
+ docs.push(this.version, handlerType, constants_1.HANDLER_METHOD_MAP[handlerType], url, model);
173
128
  });
174
129
  }
175
- requestHandler(handlerType, req, res, model, parentModel, relation) {
176
- return __awaiter(this, void 0, void 0, function* () {
177
- let trx = null;
178
- let hasTransaction = false;
179
- try {
180
- const database = (yield Services_1.IoCService.use("Database"));
181
- const api = Services_1.APIService.getInstance();
182
- hasTransaction = yield new Resolvers_1.TransactionResolver(this.version).resolve(model, handlerType);
183
- if (hasTransaction) {
184
- trx = yield database.transaction();
185
- }
186
- const handler = HandlerFactory_1.default.get(handlerType);
187
- const pack = {
188
- api,
189
- version: this.version,
190
- req,
191
- res,
192
- handlerType,
193
- model,
194
- parentModel,
195
- relation,
196
- database: hasTransaction && trx ? trx : database,
197
- };
198
- yield handler(pack);
199
- if (hasTransaction && trx) {
200
- trx.commit();
201
- }
202
- }
203
- catch (error) {
204
- if (hasTransaction && trx) {
205
- trx.rollback();
206
- }
207
- this.sendErrorAsResponse(res, error);
208
- }
209
- });
210
- }
211
- sendErrorAsResponse(res, error) {
212
- const type = error.type;
213
- if (type === "ApiError") {
214
- // eslint-disable-next-line no-case-declarations
215
- const apiError = error;
216
- res.status(apiError.status).json({
217
- error: apiError.message,
218
- });
219
- return;
220
- }
221
- // We should log error and send general error response
222
- Services_1.LogService.getInstance().error(`SERVER ERROR: ${JSON.stringify(Object.assign(Object.assign({}, error), { message: error.message }), null, " ")}`);
223
- throw error;
224
- }
225
130
  getResourcePath(model, relation) {
226
131
  return relation
227
132
  ? (0, change_case_1.paramCase)(relation.name)
@@ -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 = {}));
@@ -1,3 +1,4 @@
1
- import { Request, Response } from "express";
2
- declare const _default: (req: Request, res: Response) => Promise<void>;
1
+ import AxeRequest from "../Services/AxeRequest";
2
+ import AxeResponse from "../Services/AxeResponse";
3
+ declare const _default: (req: AxeRequest, res: AxeResponse) => Promise<void>;
3
4
  export default _default;
@@ -1,17 +1,17 @@
1
- import { Request } from "express";
2
- import { IModelService, IRelation, IHookParameter, IQuery, IVersion, IWith } from "../Interfaces";
1
+ import { IModelService, IRelation, IQuery, IVersion, IWith, IRequestPack } from "../Interfaces";
3
2
  import { Knex } from "knex";
4
3
  import { HandlerTypes, HookFunctionTypes, TimestampColumns } from "../Enums";
5
4
  import { ModelListService } from "../Services";
6
5
  import { SerializationFunction } from "../Types";
6
+ import AxeRequest from "src/Services/AxeRequest";
7
7
  export declare const bindTimestampValues: (formData: Record<string, any>, model: IModelService, columnTypes?: TimestampColumns[]) => void;
8
- export declare const getMergedFormData: (req: Request, fillables: string[]) => Record<string, any>;
9
- export declare const callHooks: (model: IModelService, type: HookFunctionTypes, params: IHookParameter) => Promise<void>;
8
+ export declare const getMergedFormData: (req: AxeRequest, fillables: string[]) => Record<string, any>;
9
+ export declare const callHooks: (model: IModelService, type: HookFunctionTypes, params: IRequestPack) => Promise<void>;
10
10
  export declare const getParentColumn: (relation: IRelation | null) => string | null;
11
11
  export declare const checkPrimaryKeyValueType: (model: IModelService, value: any) => void;
12
- export declare const addForeignKeyQuery: (request: Request, query: Knex.QueryBuilder, relation: IRelation | null, parentModel: IModelService | null) => void;
13
- export declare const serializeData: (version: IVersion, itemArray: any, modelSerializer: SerializationFunction | null, handler: HandlerTypes, request: Request) => Promise<any[]>;
12
+ export declare const addForeignKeyQuery: (request: AxeRequest, query: Knex.QueryBuilder, relation: IRelation | null, parentModel: IModelService | null) => void;
13
+ export declare const serializeData: (version: IVersion, itemArray: any, modelSerializer: SerializationFunction | null, handler: HandlerTypes, request: AxeRequest) => Promise<any[]>;
14
14
  export declare const filterHiddenFields: (itemArray: any[], hiddens: string[] | null) => void;
15
15
  export declare const addSoftDeleteQuery: (model: IModelService, conditions: IQuery | null, query: Knex.QueryBuilder) => void;
16
- export declare const getRelatedData: (version: IVersion, data: any[], withArray: IWith[], model: IModelService, modelList: ModelListService, database: Knex | Knex.Transaction, handler: HandlerTypes, request: Request) => Promise<void>;
16
+ export declare const getRelatedData: (version: IVersion, data: any[], withArray: IWith[], model: IModelService, modelList: ModelListService, database: Knex | Knex.Transaction, handler: HandlerTypes, request: AxeRequest) => Promise<void>;
17
17
  export declare const isBoolean: (value: any) => boolean;
@@ -1,3 +1,4 @@
1
- import { Request, Response } from "express";
2
- declare const _default: (req: Request, res: Response) => Promise<void>;
1
+ import AxeRequest from "../Services/AxeRequest";
2
+ import AxeResponse from "../Services/AxeResponse";
3
+ declare const _default: (req: AxeRequest, res: AxeResponse) => Promise<void>;
3
4
  export default _default;
@@ -0,0 +1,3 @@
1
+ import { IncomingMessage, ServerResponse } from "http";
2
+ declare const _default: (request: IncomingMessage, response: ServerResponse) => Promise<void>;
3
+ export default _default;
@@ -0,0 +1,99 @@
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 Services_1 = require("../Services");
16
+ const URLService_1 = __importDefault(require("../Services/URLService"));
17
+ const ConverterService_1 = require("../Services/ConverterService");
18
+ const api = Services_1.APIService.getInstance();
19
+ const return404 = (response) => {
20
+ response.statusCode = 404;
21
+ response.write(JSON.stringify({ error: "Resource not found" }));
22
+ response.end();
23
+ };
24
+ const callPhases = (phases, context, match, trx, axeResponse) => __awaiter(void 0, void 0, void 0, function* () {
25
+ for (const phase of phases) {
26
+ // If there is an non-async phase, it should be an Event function
27
+ if (phase.isAsync === false) {
28
+ Services_1.LogService.debug(`\t${phase.name}()`);
29
+ yield phase.callback(context);
30
+ continue;
31
+ }
32
+ // Middleware and hook calls
33
+ try {
34
+ Services_1.LogService.debug(`\t${phase.name}()`);
35
+ yield phase.callback(context);
36
+ }
37
+ catch (error) {
38
+ Services_1.LogService.error(`\t${error.message} ${phase.callback}`);
39
+ // Rollback transaction
40
+ if (match.hasTransaction && trx) {
41
+ Services_1.LogService.warn("\tDB transaction rollback");
42
+ trx.rollback();
43
+ }
44
+ if (error.type === "ApiError") {
45
+ const apiError = error;
46
+ return axeResponse
47
+ .status(apiError.status)
48
+ .json({ error: apiError.message });
49
+ }
50
+ // TODO: We need an error handler.
51
+ axeResponse.status(500).json({ error: error.toString() });
52
+ break;
53
+ }
54
+ // If the response is not created, we should go to the next phase
55
+ if (context.res.isResponded() === false) {
56
+ continue;
57
+ }
58
+ // If the response is an error, and we have an active transaction,
59
+ // we should rollback it before the HTTP request end.
60
+ if (context.res.statusCode() >= 400 && context.res.statusCode() < 599) {
61
+ if (match.hasTransaction && trx) {
62
+ Services_1.LogService.warn("\tDB transaction rollback");
63
+ trx.rollback();
64
+ }
65
+ Services_1.LogService.debug(`\tResponse ${context.res.statusCode()}`);
66
+ break;
67
+ }
68
+ // If there is a valid transaction, we should commit it
69
+ if (match.hasTransaction && trx) {
70
+ Services_1.LogService.warn("\tDB transaction commit");
71
+ trx.commit();
72
+ }
73
+ Services_1.LogService.debug(`\tResponse ${context.res.statusCode()}`);
74
+ // We should brake the for-loop
75
+ break;
76
+ }
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,4 @@
1
- import { Request, Response } from "express";
2
- declare const _default: (req: Request, res: Response) => Promise<void>;
1
+ import AxeRequest from "../Services/AxeRequest";
2
+ import AxeResponse from "../Services/AxeResponse";
3
+ declare const _default: (req: AxeRequest, res: AxeResponse) => Promise<void>;
3
4
  export default _default;
@@ -1,4 +1,2 @@
1
- import { Request } from "express";
2
1
  import { IVersion } from "./Interfaces";
3
- export declare const getVersionByRequest: (req: Request) => Promise<IVersion>;
4
- export declare const consoleAxeError: (error: any) => void;
2
+ export declare const getVersionByRequest: (urlObject: URL) => IVersion | undefined;
@@ -1,78 +1,14 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.consoleAxeError = exports.getVersionByRequest = void 0;
16
- const chalk_1 = __importDefault(require("chalk"));
17
- const change_case_1 = require("change-case");
3
+ exports.getVersionByRequest = void 0;
18
4
  const Services_1 = require("./Services");
19
- const getVersionByRequest = (req) => __awaiter(void 0, void 0, void 0, function* () {
5
+ const getVersionByRequest = (urlObject) => {
20
6
  // Application configuration is need for the default setting.
21
7
  const api = Services_1.APIService.getInstance();
22
8
  const matchedVersion = api.versions.find((version) => {
23
9
  const path = `/${api.config.prefix}/${version.name}`;
24
- return req.path.indexOf(path) === 0;
10
+ return urlObject.pathname.startsWith(path);
25
11
  });
26
- if (!matchedVersion) {
27
- throw new Error(`Version is not matched: ${req.path}`);
28
- }
29
12
  return matchedVersion;
30
- });
31
- exports.getVersionByRequest = getVersionByRequest;
32
- const consoleAxeError = (error) => {
33
- const putWithSpace = (text, max) => {
34
- const diff = max - text.length + 3;
35
- for (let index = 0; index <= diff; index++) {
36
- text = `${text} `;
37
- }
38
- text = ` ${text}`;
39
- if (text.length > 77) {
40
- let lines = [];
41
- text = text.trim();
42
- for (let step = 0; step < text.length / 70; step++) {
43
- lines.push(text.substring(0, 70));
44
- text = text.substring(70);
45
- }
46
- lines.push(text);
47
- lines = lines.map((line) => putWithSpace(line, max));
48
- return lines.flat();
49
- }
50
- return [text];
51
- };
52
- const getMaxLength = (code, message) => {
53
- let maxLength = message.length;
54
- if (code.length > message.length) {
55
- maxLength = code.length;
56
- }
57
- if (maxLength > 70) {
58
- maxLength = 70;
59
- }
60
- return maxLength;
61
- };
62
- const maxLength = getMaxLength(error.code, error.message);
63
- const messages = [
64
- "\n",
65
- ...putWithSpace(" ", maxLength),
66
- ...putWithSpace(`[${error.code}]`, maxLength),
67
- ...putWithSpace(" ", maxLength),
68
- ...putWithSpace(error.message, maxLength),
69
- ...putWithSpace(" ", maxLength),
70
- ];
71
- console.log(chalk_1.default.bgRed.white(messages.join("\n")));
72
- console.log(chalk_1.default.cyan([
73
- "\n",
74
- "You can find more in the documentation;",
75
- `https://axe-api.com/errors.html#${(0, change_case_1.paramCase)(error.code)}`,
76
- ].join("\n")));
77
13
  };
78
- exports.consoleAxeError = consoleAxeError;
14
+ exports.getVersionByRequest = getVersionByRequest;