axe-api 0.31.3 → 1.0.0-rc1

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 (129) 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 +2 -2
  4. package/build/index.js +4 -1
  5. package/build/src/Builders/RouterBuilder.d.ts +0 -4
  6. package/build/src/Builders/RouterBuilder.js +13 -107
  7. package/build/src/Handlers/DocsHTMLHandler.d.ts +3 -2
  8. package/build/src/Handlers/Helpers.d.ts +7 -7
  9. package/build/src/Handlers/Helpers.js +2 -1
  10. package/build/src/Handlers/MetadataHandler.d.ts +3 -2
  11. package/build/src/Handlers/RequestHandler.d.ts +3 -0
  12. package/build/src/Handlers/RequestHandler.js +89 -0
  13. package/build/src/Handlers/RoutesHandler.d.ts +3 -2
  14. package/build/src/Helpers.d.ts +1 -2
  15. package/build/src/Helpers.js +3 -15
  16. package/build/src/Interfaces.d.ts +30 -29
  17. package/build/src/Model.d.ts +3 -3
  18. package/build/src/Phases/All/FetchPhase.d.ts +3 -0
  19. package/build/src/Phases/All/FetchPhase.js +16 -0
  20. package/build/src/Phases/All/PreparePhase.d.ts +3 -0
  21. package/build/src/Phases/All/PreparePhase.js +30 -0
  22. package/build/src/Phases/All/index.d.ts +4 -0
  23. package/build/src/{Middlewares → Phases/All}/index.js +4 -3
  24. package/build/src/Phases/Delete/ActionPhase.d.ts +3 -0
  25. package/build/src/Phases/Delete/ActionPhase.js +24 -0
  26. package/build/src/Phases/Delete/PreparePhase.d.ts +3 -0
  27. package/build/src/Phases/Delete/PreparePhase.js +25 -0
  28. package/build/src/Phases/Delete/QueryPhase.d.ts +3 -0
  29. package/build/src/Phases/Delete/QueryPhase.js +20 -0
  30. package/build/src/Phases/Delete/ResponsePhase.d.ts +3 -0
  31. package/build/src/Phases/Delete/ResponsePhase.js +14 -0
  32. package/build/src/Phases/Delete/index.d.ts +7 -0
  33. package/build/src/Phases/Delete/index.js +15 -0
  34. package/build/src/Phases/ForceDelete/ActionPhase.d.ts +3 -0
  35. package/build/src/Phases/ForceDelete/ActionPhase.js +16 -0
  36. package/build/src/Phases/ForceDelete/PreparePhase.d.ts +3 -0
  37. package/build/src/Phases/ForceDelete/PreparePhase.js +28 -0
  38. package/build/src/Phases/ForceDelete/QueryPhase.d.ts +3 -0
  39. package/build/src/Phases/ForceDelete/QueryPhase.js +20 -0
  40. package/build/src/Phases/ForceDelete/index.d.ts +6 -0
  41. package/build/src/Phases/ForceDelete/index.js +13 -0
  42. package/build/src/Phases/List/RelationalPhase.d.ts +3 -0
  43. package/build/src/Phases/List/RelationalPhase.js +17 -0
  44. package/build/src/Phases/List/ResultPhase.d.ts +3 -0
  45. package/build/src/Phases/List/ResultPhase.js +14 -0
  46. package/build/src/Phases/List/SerializePhase.d.ts +3 -0
  47. package/build/src/Phases/List/SerializePhase.js +19 -0
  48. package/build/src/Phases/List/index.d.ts +6 -0
  49. package/build/src/Phases/List/index.js +13 -0
  50. package/build/src/Phases/Paginate/FetchPhase.d.ts +3 -0
  51. package/build/src/Phases/Paginate/FetchPhase.js +19 -0
  52. package/build/src/Phases/Paginate/PreparePhase.d.ts +3 -0
  53. package/build/src/Phases/Paginate/PreparePhase.js +30 -0
  54. package/build/src/Phases/Paginate/index.d.ts +5 -0
  55. package/build/src/Phases/Paginate/index.js +11 -0
  56. package/build/src/Phases/Patch/PrepareActionPhase.d.ts +3 -0
  57. package/build/src/Phases/Patch/PrepareActionPhase.js +37 -0
  58. package/build/src/Phases/Patch/index.d.ts +4 -0
  59. package/build/src/Phases/Patch/index.js +9 -0
  60. package/build/src/Phases/Show/FetchPhase.d.ts +3 -0
  61. package/build/src/Phases/Show/FetchPhase.js +23 -0
  62. package/build/src/Phases/Show/PreparePhase.d.ts +3 -0
  63. package/build/src/Phases/Show/PreparePhase.js +31 -0
  64. package/build/src/Phases/Show/index.d.ts +5 -0
  65. package/build/src/Phases/Show/index.js +11 -0
  66. package/build/src/Phases/Single/GetPhase.d.ts +3 -0
  67. package/build/src/{Middlewares/acceptLanguageMiddleware.js → Phases/Single/GetPhase.js} +15 -10
  68. package/build/src/Phases/Single/PrepareGetPhase.d.ts +3 -0
  69. package/build/src/Phases/Single/PrepareGetPhase.js +19 -0
  70. package/build/src/Phases/Single/RelationalPhase.d.ts +3 -0
  71. package/build/src/Phases/Single/RelationalPhase.js +17 -0
  72. package/build/src/Phases/Single/ResultPhase.d.ts +3 -0
  73. package/build/src/Phases/Single/ResultPhase.js +14 -0
  74. package/build/src/Phases/Single/SerializePhase.d.ts +3 -0
  75. package/build/src/Phases/Single/SerializePhase.js +18 -0
  76. package/build/src/Phases/Single/index.d.ts +8 -0
  77. package/build/src/Phases/Single/index.js +17 -0
  78. package/build/src/Phases/Store/ActionPhase.d.ts +3 -0
  79. package/build/src/Phases/Store/ActionPhase.js +29 -0
  80. package/build/src/Phases/Store/PreparePhase.d.ts +3 -0
  81. package/build/src/Phases/Store/PreparePhase.js +46 -0
  82. package/build/src/Phases/Store/index.d.ts +5 -0
  83. package/build/src/Phases/Store/index.js +11 -0
  84. package/build/src/Phases/Update/ActionPhase.d.ts +3 -0
  85. package/build/src/Phases/Update/ActionPhase.js +22 -0
  86. package/build/src/Phases/Update/PrepareActionPhase.d.ts +3 -0
  87. package/build/src/Phases/Update/PrepareActionPhase.js +37 -0
  88. package/build/src/Phases/Update/index.d.ts +5 -0
  89. package/build/src/Phases/Update/index.js +11 -0
  90. package/build/src/Server.d.ts +0 -1
  91. package/build/src/Server.js +13 -16
  92. package/build/src/Services/App.d.ts +14 -0
  93. package/build/src/Services/App.js +37 -0
  94. package/build/src/Services/AxeRequest.d.ts +24 -0
  95. package/build/src/Services/AxeRequest.js +59 -0
  96. package/build/src/Services/AxeResponse.d.ts +17 -0
  97. package/build/src/Services/AxeResponse.js +38 -0
  98. package/build/src/Services/LogService.js +4 -5
  99. package/build/src/Services/ModelService.d.ts +4 -4
  100. package/build/src/Services/QueryService.d.ts +1 -1
  101. package/build/src/Services/QueryService.js +14 -19
  102. package/build/src/Services/URLService.d.ts +29 -0
  103. package/build/src/Services/URLService.js +116 -0
  104. package/build/src/Services/index.d.ts +4 -1
  105. package/build/src/Services/index.js +7 -1
  106. package/build/src/Types.d.ts +7 -6
  107. package/build/src/constants.d.ts +10 -2
  108. package/build/src/constants.js +163 -1
  109. package/package.json +9 -1
  110. package/build/src/Handlers/AllHandler.d.ts +0 -3
  111. package/build/src/Handlers/AllHandler.js +0 -45
  112. package/build/src/Handlers/DestroyHandler.d.ts +0 -3
  113. package/build/src/Handlers/DestroyHandler.js +0 -51
  114. package/build/src/Handlers/ForceDestroyHandler.d.ts +0 -3
  115. package/build/src/Handlers/ForceDestroyHandler.js +0 -45
  116. package/build/src/Handlers/HandlerFactory.d.ts +0 -6
  117. package/build/src/Handlers/HandlerFactory.js +0 -39
  118. package/build/src/Handlers/PaginateHandler.d.ts +0 -3
  119. package/build/src/Handlers/PaginateHandler.js +0 -49
  120. package/build/src/Handlers/PatchHandler.d.ts +0 -3
  121. package/build/src/Handlers/PatchHandler.js +0 -69
  122. package/build/src/Handlers/ShowHandler.d.ts +0 -3
  123. package/build/src/Handlers/ShowHandler.js +0 -55
  124. package/build/src/Handlers/StoreHandler.d.ts +0 -3
  125. package/build/src/Handlers/StoreHandler.js +0 -65
  126. package/build/src/Handlers/UpdateHandler.d.ts +0 -3
  127. package/build/src/Handlers/UpdateHandler.js +0 -69
  128. package/build/src/Middlewares/acceptLanguageMiddleware.d.ts +0 -3
  129. 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,7 @@ 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
6
  export * from "./src/Enums";
7
7
  export * from "./src/Interfaces";
8
- export { Server, Model, ApiError, DEFAULT_HANDLERS, DEFAULT_VERSION_CONFIG, IoCService, allow, deny, };
8
+ export { App, AxeRequest, AxeResponse, Server, Model, ApiError, DEFAULT_HANDLERS, DEFAULT_VERSION_CONFIG, IoCService, allow, deny, };
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.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,8 @@ 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; } });
34
37
  __exportStar(require("./src/Enums"), exports);
35
38
  __exportStar(require("./src/Interfaces"), exports);
@@ -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
10
  private addExpressRoute;
13
- private requestHandler;
14
- private sendErrorAsResponse;
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
  }
@@ -82,7 +74,6 @@ class RouterBuilder {
82
74
  // internal middlewares such as `Accept Language Middleware` which parse
83
75
  // the "accept-language" header to use in the application general.
84
76
  const middlewares = [
85
- Middlewares_1.acceptLanguageMiddleware,
86
77
  ...model.instance.getMiddlewares(handlerType),
87
78
  ];
88
79
  // Adding the route to the express
@@ -124,104 +115,19 @@ class RouterBuilder {
124
115
  addExpressRoute(handlerType, url, middlewares, model, parentModel, relation) {
125
116
  return __awaiter(this, void 0, void 0, function* () {
126
117
  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
- }
118
+ const data = {
119
+ version: this.version,
120
+ handlerType,
121
+ model,
122
+ parentModel,
123
+ relation,
124
+ };
125
+ // Adding the route
126
+ yield URLService_1.default.add(constants_1.HANDLER_METHOD_MAP[handlerType], url, data, middlewares);
127
+ // Documentation
128
+ docs.push(this.version, handlerType, constants_1.HANDLER_METHOD_MAP[handlerType], url, model);
173
129
  });
174
130
  }
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
131
  getResourcePath(model, relation) {
226
132
  return relation
227
133
  ? (0, change_case_1.paramCase)(relation.name)
@@ -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;
@@ -67,7 +67,8 @@ exports.getParentColumn = getParentColumn;
67
67
  const checkPrimaryKeyValueType = (model, value) => {
68
68
  // We should check the parameter type
69
69
  const primaryColumn = model.columns.find((column) => column.name === model.instance.primaryKey);
70
- if ((primaryColumn === null || primaryColumn === void 0 ? void 0 : primaryColumn.data_type) === "integer" && isNaN(parseInt(value))) {
70
+ if (constants_1.NUMERIC_PRIMARY_KEY_TYPES.includes((primaryColumn === null || primaryColumn === void 0 ? void 0 : primaryColumn.data_type) || "") &&
71
+ isNaN(parseInt(value))) {
71
72
  throw new ApiError_1.default(`Unacceptable parameter: ${value}`);
72
73
  }
73
74
  };
@@ -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,89 @@
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 AxeRequest_1 = __importDefault(require("../Services/AxeRequest"));
18
+ const AxeResponse_1 = __importDefault(require("../Services/AxeResponse"));
19
+ const api = Services_1.APIService.getInstance();
20
+ const return404 = (response) => {
21
+ response.statusCode = 404;
22
+ response.write(JSON.stringify({ error: "Resource not found" }));
23
+ response.end();
24
+ };
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) {
48
+ // If there is an non-async phase, it should be an Event function
49
+ if (phase.isAsync === false) {
50
+ yield phase.callback(pack);
51
+ continue;
52
+ }
53
+ // Middleware and hook calls
54
+ try {
55
+ yield phase.callback(pack);
56
+ }
57
+ catch (error) {
58
+ // Rollback transaction
59
+ if (match.hasTransaction && trx) {
60
+ trx.rollback();
61
+ }
62
+ if (error.type === "ApiError") {
63
+ const apiError = error;
64
+ return axeResponse.json({ error: apiError.message }, apiError.status);
65
+ }
66
+ // TODO: We need an error handler.
67
+ axeResponse.json({ error: error.toString() }, 500);
68
+ break;
69
+ }
70
+ // If the response is not created, we should go to the next phase
71
+ if (pack.res.isResponded() === false) {
72
+ continue;
73
+ }
74
+ // If the response is an error, and we have an active transaction,
75
+ // we should rollback it before the HTTP request end.
76
+ if (pack.res.statusCode() >= 400 && pack.res.statusCode() < 599) {
77
+ if (match.hasTransaction && trx) {
78
+ trx.rollback();
79
+ }
80
+ break;
81
+ }
82
+ // If there is a valid transaction, we should commit it
83
+ if (match.hasTransaction && trx) {
84
+ trx.commit();
85
+ }
86
+ // We should brake the for-loop
87
+ break;
88
+ }
89
+ });
@@ -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,3 @@
1
- import { Request } from "express";
2
1
  import { IVersion } from "./Interfaces";
3
- export declare const getVersionByRequest: (req: Request) => Promise<IVersion>;
2
+ export declare const getVersionByRequest: (urlObject: URL) => IVersion | undefined;
4
3
  export declare const consoleAxeError: (error: any) => void;
@@ -1,13 +1,4 @@
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -16,18 +7,15 @@ exports.consoleAxeError = exports.getVersionByRequest = void 0;
16
7
  const chalk_1 = __importDefault(require("chalk"));
17
8
  const change_case_1 = require("change-case");
18
9
  const Services_1 = require("./Services");
19
- const getVersionByRequest = (req) => __awaiter(void 0, void 0, void 0, function* () {
10
+ const getVersionByRequest = (urlObject) => {
20
11
  // Application configuration is need for the default setting.
21
12
  const api = Services_1.APIService.getInstance();
22
13
  const matchedVersion = api.versions.find((version) => {
23
14
  const path = `/${api.config.prefix}/${version.name}`;
24
- return req.path.indexOf(path) === 0;
15
+ return urlObject.pathname.startsWith(path);
25
16
  });
26
- if (!matchedVersion) {
27
- throw new Error(`Version is not matched: ${req.path}`);
28
- }
29
17
  return matchedVersion;
30
- });
18
+ };
31
19
  exports.getVersionByRequest = getVersionByRequest;
32
20
  const consoleAxeError = (error) => {
33
21
  const putWithSpace = (text, max) => {
@@ -1,10 +1,12 @@
1
1
  import { Knex } from "knex";
2
- import { Express, Request, Response, NextFunction } from "express";
3
2
  import { Column } from "knex-schema-inspector/lib/types/column";
4
3
  import { HandlerTypes, LogLevels, HttpMethods, HookFunctionTypes, Extensions, Relationships, SortTypes, ConditionTypes, DependencyTypes, QueryFeature, QueryFeatureType } from "./Enums";
5
4
  import Model from "./Model";
6
- import { HookFunction, SerializationFunction } from "./Types";
7
- import { ModelListService } from "./Services";
5
+ import { PhaseFunction, SerializationFunction } from "./Types";
6
+ import { ModelListService, QueryService } from "./Services";
7
+ import AxeRequest from "./Services/AxeRequest";
8
+ import AxeResponse from "./Services/AxeResponse";
9
+ import App from "./Services/App";
8
10
  export interface IColumn extends Column {
9
11
  table_name: string;
10
12
  }
@@ -16,7 +18,7 @@ export interface IHandlerBasedTransactionConfig {
16
18
  }
17
19
  interface IHandlerBasedSerializer {
18
20
  handler: HandlerTypes[];
19
- serializer: ((data: any, request: Request) => void)[];
21
+ serializer: ((data: any, request: AxeRequest) => void)[];
20
22
  }
21
23
  export interface IQueryLimitConfig {
22
24
  feature: QueryFeature;
@@ -34,7 +36,7 @@ export interface IQueryConfig {
34
36
  }
35
37
  export interface IVersionConfig {
36
38
  transaction: boolean | IHandlerBasedTransactionConfig | IHandlerBasedTransactionConfig[];
37
- serializers: ((data: any, request: Request) => void)[] | IHandlerBasedSerializer[];
39
+ serializers: ((data: any, request: AxeRequest) => void)[] | IHandlerBasedSerializer[];
38
40
  supportedLanguages: string[];
39
41
  defaultLanguage: string;
40
42
  query: IQueryConfig;
@@ -79,26 +81,12 @@ export interface IAPI {
79
81
  config: IApplicationConfig;
80
82
  }
81
83
  export interface IGeneralHooks {
82
- onBeforeInit: (app: Express) => void | null;
83
- onAfterInit: (app: Express) => void | null;
84
+ onBeforeInit: (app: App) => void | null;
85
+ onAfterInit: (app: App) => void | null;
84
86
  }
85
87
  export interface IHandlerBaseMiddleware {
86
88
  handler: HandlerTypes[];
87
- middleware: (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
88
- }
89
- export interface IHookParameter {
90
- req: Request;
91
- res: Response;
92
- handlerType: HandlerTypes;
93
- model: IModelService;
94
- parentModel: IModelService | null;
95
- relation: IRelation | null;
96
- database: Knex | Knex.Transaction;
97
- conditions: IQuery | null;
98
- query: Knex.QueryBuilder | null;
99
- result: any;
100
- item: any;
101
- formData: any;
89
+ middleware: (context: IRequestPack) => Promise<void>;
102
90
  }
103
91
  export interface IMethodBaseConfig {
104
92
  [HttpMethods.POST]?: string[];
@@ -115,14 +103,14 @@ export interface IModelService {
115
103
  relations: IRelation[];
116
104
  columns: IColumn[];
117
105
  columnNames: string[];
118
- hooks: Record<HookFunctionTypes, HookFunction>;
119
- events: Record<HookFunctionTypes, HookFunction>;
106
+ hooks: Record<HookFunctionTypes, PhaseFunction>;
107
+ events: Record<HookFunctionTypes, PhaseFunction>;
120
108
  isRecursive: boolean;
121
109
  children: IModelService[];
122
110
  queryLimits: IQueryLimitConfig[];
123
111
  serialize: SerializationFunction | null;
124
112
  setColumns(columns: IColumn[]): void;
125
- setExtensions(type: Extensions, hookFunctionType: HookFunctionTypes, data: HookFunction): void;
113
+ setExtensions(type: Extensions, hookFunctionType: HookFunctionTypes, data: PhaseFunction): void;
126
114
  setQueryLimits(limits: IQueryLimitConfig[]): void;
127
115
  setSerialization(callback: SerializationFunction): void;
128
116
  }
@@ -133,16 +121,25 @@ export interface IRelation {
133
121
  primaryKey: string;
134
122
  foreignKey: string;
135
123
  }
136
- export interface IRequestPack {
137
- api: IAPI;
124
+ export interface IRouteData {
138
125
  version: IVersion;
139
- req: Request;
140
- res: Response;
141
126
  handlerType: HandlerTypes;
142
127
  model: IModelService;
143
128
  parentModel: IModelService | null;
144
129
  relation: IRelation | null;
130
+ }
131
+ export interface IRequestPack extends IRouteData {
132
+ api: IAPI;
133
+ req: AxeRequest;
134
+ res: AxeResponse;
145
135
  database: Knex | Knex.Transaction;
136
+ queryParser?: QueryService;
137
+ conditions?: IQuery;
138
+ query?: Knex.QueryBuilder;
139
+ params?: any;
140
+ result?: any;
141
+ item?: any;
142
+ formData?: any;
146
143
  }
147
144
  export interface IRouteDocumentation {
148
145
  version: string;
@@ -202,4 +199,8 @@ export interface IDependency {
202
199
  callback: any;
203
200
  instance: any;
204
201
  }
202
+ export interface IPhaseDefinition {
203
+ isAsync: boolean;
204
+ callback: PhaseFunction;
205
+ }
205
206
  export {};
@@ -1,13 +1,13 @@
1
1
  import { IRelation, IMethodBaseConfig, IMethodBaseValidations, IHandlerBaseMiddleware, IHandlerBasedTransactionConfig, IQueryLimitConfig } from "./Interfaces";
2
2
  import { HandlerTypes, HttpMethods } from "./Enums";
3
- import { FieldList, MiddlewareFunction, ModelValidation } from "./Types";
3
+ import { FieldList, ModelValidation, PhaseFunction } from "./Types";
4
4
  declare class Model {
5
5
  get primaryKey(): string;
6
6
  get table(): string;
7
7
  get fillable(): FieldList | IMethodBaseConfig;
8
8
  get validations(): IMethodBaseValidations | ModelValidation;
9
9
  get handlers(): HandlerTypes[];
10
- get middlewares(): MiddlewareFunction[] | IHandlerBaseMiddleware[] | IHandlerBaseMiddleware;
10
+ get middlewares(): PhaseFunction[] | IHandlerBaseMiddleware[] | IHandlerBaseMiddleware;
11
11
  get hiddens(): FieldList;
12
12
  get createdAtColumn(): string | null;
13
13
  get updatedAtColumn(): string | null;
@@ -17,7 +17,7 @@ declare class Model {
17
17
  get limits(): Array<IQueryLimitConfig[]>;
18
18
  getFillableFields(methodType: HttpMethods): string[];
19
19
  getValidationRules(methodType: HttpMethods): ModelValidation | null;
20
- getMiddlewares(handlerType: HandlerTypes): MiddlewareFunction[];
20
+ getMiddlewares(handlerType: HandlerTypes): PhaseFunction[];
21
21
  hasMany(relatedModel: string, primaryKey?: string, foreignKey?: string): IRelation;
22
22
  hasOne(relatedModel: string, primaryKey?: string, foreignKey?: string): IRelation;
23
23
  belongsTo(relatedModel: string, primaryKey: string, foreignKey: string): IRelation;
@@ -0,0 +1,3 @@
1
+ import { IRequestPack } from "../../Interfaces";
2
+ declare const _default: (context: IRequestPack) => Promise<void>;
3
+ export default _default;
@@ -0,0 +1,16 @@
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
+ exports.default = (context) => __awaiter(void 0, void 0, void 0, function* () {
13
+ if (context.query) {
14
+ context.result = yield context.query;
15
+ }
16
+ });
@@ -0,0 +1,3 @@
1
+ import { IRequestPack } from "../../Interfaces";
2
+ declare const _default: (context: IRequestPack) => Promise<void>;
3
+ export default _default;
@@ -0,0 +1,30 @@
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 Services_1 = require("../../Services");
13
+ const Helpers_1 = require("../../Handlers/Helpers");
14
+ exports.default = (context) => __awaiter(void 0, void 0, void 0, function* () {
15
+ context.queryParser = new Services_1.QueryService(context.model, context.version.modelList.get(), context.version.config);
16
+ // We should parse URL query string to use as condition in Lucid query
17
+ context.conditions = context.queryParser.get(context.req.query);
18
+ // Creating a new database query
19
+ context.query = context.database.from(context.model.instance.table);
20
+ // If there is a deletedAtColumn, it means that this table support soft-delete
21
+ (0, Helpers_1.addSoftDeleteQuery)(context.model, context.conditions, context.query);
22
+ // Users should be able to select some fields to show.
23
+ context.queryParser.applyFields(context.query, context.conditions.fields);
24
+ // Binding parent id if there is.
25
+ (0, Helpers_1.addForeignKeyQuery)(context.req, context.query, context.relation, context.parentModel);
26
+ // Users should be able to filter records
27
+ context.queryParser.applyWheres(context.query, context.conditions.q);
28
+ // User should be able to select sorting fields and types
29
+ context.queryParser.applySorting(context.query, context.conditions.sort);
30
+ });
@@ -0,0 +1,4 @@
1
+ declare const _default: {
2
+ FetchPhase: (context: import("../../Interfaces").IRequestPack) => Promise<void>;
3
+ };
4
+ export default _default;
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.acceptLanguageMiddleware = void 0;
7
- const acceptLanguageMiddleware_1 = __importDefault(require("./acceptLanguageMiddleware"));
8
- exports.acceptLanguageMiddleware = acceptLanguageMiddleware_1.default;
6
+ const FetchPhase_1 = __importDefault(require("./FetchPhase"));
7
+ exports.default = {
8
+ FetchPhase: FetchPhase_1.default,
9
+ };
@@ -0,0 +1,3 @@
1
+ import { IRequestPack } from "../../Interfaces";
2
+ declare const _default: (context: IRequestPack) => Promise<void>;
3
+ export default _default;