@expressots/adapter-express 1.2.0 → 1.2.1

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.
package/lib/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
 
2
2
 
3
+ ## [1.2.1](https://github.com/expressots/adapter-express/compare/1.2.0...1.2.1) (2024-04-04)
4
+
5
+
6
+ ### Code Refactoring
7
+
8
+ * adapter expressto to be used in AppFactory ([239501e](https://github.com/expressots/adapter-express/commit/239501e41bfd98ecc0893a50c34de58dd8914d9e))
9
+ * rename items for standardization and improve doc ([2e691d5](https://github.com/expressots/adapter-express/commit/2e691d50731e8d4d689fe4b4420daab8ba2f5803))
10
+
3
11
  ## [1.2.0](https://github.com/expressots/adapter-express/compare/1.1.1...1.2.0) (2024-3-5)
4
12
 
5
13
 
@@ -5,50 +5,32 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
6
  return c > 3 && r && Object.defineProperty(target, key, r), r;
7
7
  };
8
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
- return new (P || (P = Promise))(function (resolve, reject) {
11
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
- step((generator = generator.apply(thisArg, _arguments || [])).next());
15
- });
16
- };
17
8
  var __importDefault = (this && this.__importDefault) || function (mod) {
18
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
19
10
  };
20
11
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.ServerEnvironment = exports.AppExpress = void 0;
12
+ exports.AppExpress = void 0;
13
+ const core_1 = require("@expressots/core");
22
14
  const inversify_binding_decorators_1 = require("inversify-binding-decorators");
23
15
  const process_1 = __importDefault(require("process"));
24
- const core_1 = require("@expressots/core");
16
+ const application_express_base_1 = require("./application-express.base");
25
17
  const inversify_express_server_1 = require("./express-utils/inversify-express-server");
26
- const application_base_1 = require("./application-base");
27
- /**
28
- * Abstract class for creating custom Expresso middleware.
29
- * Custom middleware classes should extend this class and implement the use method.
30
- *
31
- */
32
- class ExpressoMiddleware {
33
- get name() {
34
- return this.constructor.name;
35
- }
36
- }
37
- /**
38
- * Enum representing possible server environments.
39
- */
40
- var ServerEnvironment;
41
- (function (ServerEnvironment) {
42
- ServerEnvironment["Development"] = "development";
43
- ServerEnvironment["Production"] = "production";
44
- })(ServerEnvironment || (exports.ServerEnvironment = ServerEnvironment = {}));
18
+ const application_express_types_1 = require("./application-express.types");
45
19
  /**
46
- * The Application class provides a way to configure and manage an Express application.
47
- * @provide Application
20
+ * The AppExpress class provides methods for configuring and running an Express application.
21
+ * @class AppExpress
22
+ * @implements {IWebServer} - Interface for the WebServer application implementation.
23
+ * @extends {ApplicationBase} - Base class for the application implementation that provides lifecycle hooks.
24
+ * @method configure - Configures the InversifyJS container.
25
+ * @method listen - Start listening on the given port and environment.
26
+ * @method setGlobalRoutePrefix - Sets the global route prefix for the application.
27
+ * @method setEngine - Configures the application's view engine based on the provided configuration options.
28
+ * @method isDevelopment - Verifies if the current environment is development.
48
29
  */
49
- let ApplicationExpress = class ApplicationExpress extends application_base_1.ApplicationBase {
30
+ let AppExpress = class AppExpress extends application_express_base_1.ApplicationBase {
50
31
  constructor() {
51
32
  super(...arguments);
33
+ this.globalPrefix = "/";
52
34
  this.middlewares = [];
53
35
  }
54
36
  configureServices() { }
@@ -61,40 +43,46 @@ let ApplicationExpress = class ApplicationExpress extends application_base_1.App
61
43
  this.serverShutdown();
62
44
  process_1.default.exit(0);
63
45
  }
46
+ /**
47
+ * Configures the InversifyJS container.
48
+ * @param container - The InversifyJS container.
49
+ */
50
+ async configure(container) {
51
+ this.container = container;
52
+ this.console = this.container.get(core_1.Console);
53
+ }
64
54
  /**
65
55
  * Configures the Express application with the provided middleware entries.
66
56
  * @param app - The Express application instance.
67
57
  * @param middlewareEntries - An array of Express middleware entries to be applied.
68
58
  */
69
- configureMiddleware(app, middlewareEntries) {
70
- return __awaiter(this, void 0, void 0, function* () {
71
- for (const entry of middlewareEntries) {
72
- if (typeof entry === "function") {
73
- app.use(entry);
74
- // eslint-disable-next-line no-prototype-builtins
75
- }
76
- else if (entry === null || entry === void 0 ? void 0 : entry.hasOwnProperty("path")) {
77
- const { path, middlewares } = entry;
78
- for (const mid of middlewares) {
79
- if (path) {
80
- if (typeof mid === "function") {
81
- app.use(path, mid);
82
- }
83
- else {
84
- const middleware = mid;
85
- middleware.use = middleware.use.bind(middleware);
86
- app.use(path, middleware.use);
87
- }
59
+ async configureMiddleware(app, middlewareEntries) {
60
+ for (const entry of middlewareEntries) {
61
+ if (typeof entry === "function") {
62
+ app.use(entry);
63
+ // eslint-disable-next-line no-prototype-builtins
64
+ }
65
+ else if (entry?.hasOwnProperty("path")) {
66
+ const { path, middlewares } = entry;
67
+ for (const mid of middlewares) {
68
+ if (path) {
69
+ if (typeof mid === "function") {
70
+ app.use(path, mid);
71
+ }
72
+ else {
73
+ const middleware = mid;
74
+ middleware.use = middleware.use.bind(middleware);
75
+ app.use(path, middleware.use);
88
76
  }
89
77
  }
90
78
  }
91
- else {
92
- const middleware = entry;
93
- middleware.use = middleware.use.bind(middleware);
94
- app.use(middleware.use);
95
- }
96
79
  }
97
- });
80
+ else {
81
+ const middleware = entry;
82
+ middleware.use = middleware.use.bind(middleware);
83
+ app.use(middleware.use);
84
+ }
85
+ }
98
86
  }
99
87
  /**
100
88
  * Create and configure the Express application.
@@ -102,41 +90,25 @@ let ApplicationExpress = class ApplicationExpress extends application_base_1.App
102
90
  * @param middlewares - An array of Express middlewares to be applied.
103
91
  * @returns The configured Application instance.
104
92
  */
105
- init(container, middlewares = []) {
106
- return __awaiter(this, void 0, void 0, function* () {
107
- yield this.configureServices();
108
- const middleware = container.get(core_1.Middleware);
109
- const sortedMiddlewarePipeline = middleware.getMiddlewarePipeline();
110
- const pipeline = sortedMiddlewarePipeline.map((entry) => entry.middleware);
111
- this.middlewares.push(...middlewares, ...pipeline);
112
- const expressServer = new inversify_express_server_1.InversifyExpressServer(container, null, {
113
- rootPath: this.globalPrefix,
114
- });
115
- expressServer.setConfig((app) => {
116
- this.configureMiddleware(app, this.middlewares);
117
- });
118
- expressServer.setErrorConfig((app) => {
119
- if (middleware.getErrorHandler()) {
120
- app.use(middleware.getErrorHandler());
121
- }
122
- });
123
- this.app = expressServer.build();
124
- return this;
93
+ async init() {
94
+ await this.configureServices();
95
+ const middleware = this.container.get(core_1.Middleware);
96
+ const sortedMiddlewarePipeline = middleware.getMiddlewarePipeline();
97
+ const pipeline = sortedMiddlewarePipeline.map((entry) => entry.middleware);
98
+ this.middlewares.push(...pipeline);
99
+ const expressServer = new inversify_express_server_1.InversifyExpressServer(this.container, null, {
100
+ rootPath: this.globalPrefix,
125
101
  });
126
- }
127
- /**
128
- * Create and configure the Express application.
129
- * @param container - The InversifyJS container.
130
- * @param middlewares - An array of Express middlewares to be applied.
131
- * @returns The configured Application instance.
132
- */
133
- create(container, middlewares = []) {
134
- return __awaiter(this, void 0, void 0, function* () {
135
- this.container = container;
136
- this.middlewares = middlewares;
137
- this.globalPrefix = this.globalPrefix || "/";
138
- return this;
102
+ expressServer.setConfig((app) => {
103
+ this.configureMiddleware(app, this.middlewares);
139
104
  });
105
+ expressServer.setErrorConfig((app) => {
106
+ if (middleware.getErrorHandler()) {
107
+ app.use(middleware.getErrorHandler());
108
+ }
109
+ });
110
+ this.app = expressServer.build();
111
+ return this;
140
112
  }
141
113
  /**
142
114
  * Start listening on the given port and environment.
@@ -144,23 +116,18 @@ let ApplicationExpress = class ApplicationExpress extends application_base_1.App
144
116
  * @param environment - The server environment.
145
117
  * @param consoleMessage - Optional message to display in the console.
146
118
  */
147
- listen(port, environment, consoleMessage) {
148
- return __awaiter(this, void 0, void 0, function* () {
149
- /* Initializes the application and executes the middleware pipeline */
150
- yield this.init(this.container, this.middlewares);
151
- /* Sets the port and environment */
152
- this.port = port;
153
- this.environment = environment;
154
- this.app.set("env", environment);
155
- this.app.listen(this.port, () => {
156
- const console = this.container.get(core_1.Console);
157
- console.messageServer(this.port, this.environment, consoleMessage);
158
- ["SIGTERM", "SIGHUP", "SIGBREAK", "SIGQUIT", "SIGINT"].forEach((signal) => {
159
- process_1.default.on(signal, this.handleExit.bind(this));
160
- });
119
+ async listen(port, environment, consoleMessage) {
120
+ await this.init();
121
+ this.port = port;
122
+ this.environment = environment;
123
+ this.app.set("env", environment);
124
+ this.app.listen(this.port, () => {
125
+ this.console.messageServer(this.port, this.environment, consoleMessage);
126
+ ["SIGTERM", "SIGHUP", "SIGBREAK", "SIGQUIT", "SIGINT"].forEach((signal) => {
127
+ process_1.default.on(signal, this.handleExit.bind(this));
161
128
  });
162
- yield Promise.resolve(this.postServerInitialization());
163
129
  });
130
+ await this.postServerInitialization();
164
131
  }
165
132
  /**
166
133
  * Sets the global route prefix for the application.
@@ -200,24 +167,15 @@ let ApplicationExpress = class ApplicationExpress extends application_base_1.App
200
167
  */
201
168
  isDevelopment() {
202
169
  if (this.app) {
203
- return this.app.get("env") === ServerEnvironment.Development;
170
+ return this.app.get("env") === application_express_types_1.ServerEnvironment.Development;
204
171
  }
205
172
  this.container
206
173
  .get(core_1.Logger)
207
174
  .error("isDevelopment() method must be called on `PostServerInitialization`", "application");
208
175
  return false;
209
176
  }
210
- /**
211
- * Verifies if the current environment is production.
212
- *
213
- * @returns A boolean value indicating whether the current environment is production or not.
214
- *
215
- */
216
- get ExpressApp() {
217
- return this.app;
218
- }
219
177
  };
220
- exports.AppExpress = ApplicationExpress;
221
- exports.AppExpress = ApplicationExpress = __decorate([
222
- (0, inversify_binding_decorators_1.provide)(ApplicationExpress)
223
- ], ApplicationExpress);
178
+ exports.AppExpress = AppExpress;
179
+ exports.AppExpress = AppExpress = __decorate([
180
+ (0, inversify_binding_decorators_1.provide)(AppExpress)
181
+ ], AppExpress);
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ServerEnvironment = exports.ExpressoMiddleware = void 0;
4
+ /**
5
+ * Abstract class for creating custom Expresso middleware.
6
+ * Custom middleware classes should extend this class and implement the use method.
7
+ *
8
+ */
9
+ class ExpressoMiddleware {
10
+ get name() {
11
+ return this.constructor.name;
12
+ }
13
+ }
14
+ exports.ExpressoMiddleware = ExpressoMiddleware;
15
+ /**
16
+ * Enum representing possible server environments.
17
+ */
18
+ var ServerEnvironment;
19
+ (function (ServerEnvironment) {
20
+ ServerEnvironment["Development"] = "development";
21
+ ServerEnvironment["Production"] = "production";
22
+ })(ServerEnvironment || (exports.ServerEnvironment = ServerEnvironment = {}));
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  Object.defineProperty(exports, "__esModule", { value: true });
35
26
  exports.InversifyExpressServer = void 0;
36
27
  /* eslint-disable @typescript-eslint/no-unused-vars */
@@ -97,11 +88,11 @@ class InversifyExpressServer {
97
88
  // it creates a new httpContext and attaches it to the
98
89
  // current request as metadata using Reflect
99
90
  this._app.all("*", (req, res, next) => {
100
- void (() => __awaiter(this, void 0, void 0, function* () {
101
- const httpContext = yield this._createHttpContext(req, res, next);
91
+ void (async () => {
92
+ const httpContext = await this._createHttpContext(req, res, next);
102
93
  Reflect.defineMetadata(constants_1.METADATA_KEY.httpContext, httpContext, req);
103
94
  next();
104
- }))();
95
+ })();
105
96
  });
106
97
  // register server-level middleware before anything else
107
98
  if (this._configFn) {
@@ -170,36 +161,34 @@ class InversifyExpressServer {
170
161
  target.append(name, typeof headerValue === "number" ? headerValue.toString() : headerValue);
171
162
  }
172
163
  }
173
- handleHttpResponseMessage(message, res) {
174
- return __awaiter(this, void 0, void 0, function* () {
175
- this.copyHeadersTo(message.headers, res);
176
- if (message.content !== undefined) {
177
- this.copyHeadersTo(message.content.headers, res);
178
- res
179
- .status(message.statusCode)
180
- // If the content is a number, ensure we change it to a string, else our content is
181
- // treated as a statusCode rather than as the content of the Response
182
- .send(yield message.content.readAsync());
183
- }
184
- else {
185
- res.sendStatus(message.statusCode);
186
- }
187
- });
164
+ async handleHttpResponseMessage(message, res) {
165
+ this.copyHeadersTo(message.headers, res);
166
+ if (message.content !== undefined) {
167
+ this.copyHeadersTo(message.content.headers, res);
168
+ res
169
+ .status(message.statusCode)
170
+ // If the content is a number, ensure we change it to a string, else our content is
171
+ // treated as a statusCode rather than as the content of the Response
172
+ .send(await message.content.readAsync());
173
+ }
174
+ else {
175
+ res.sendStatus(message.statusCode);
176
+ }
188
177
  }
189
178
  handlerFactory(controllerName, key, parameterMetadata) {
190
- return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
179
+ return async (req, res, next) => {
191
180
  try {
192
181
  const args = this.extractParameters(req, res, next, parameterMetadata);
193
182
  const httpContext = this._getHttpContext(req);
194
183
  httpContext.container.bind(constants_1.TYPE.HttpContext).toConstantValue(httpContext);
195
184
  // invoke controller's action
196
- const value = yield httpContext.container.getNamed(constants_1.TYPE.Controller, controllerName)[key](...args);
185
+ const value = await httpContext.container.getNamed(constants_1.TYPE.Controller, controllerName)[key](...args);
197
186
  if (value instanceof httpResponseMessage_1.HttpResponseMessage) {
198
- yield this.handleHttpResponseMessage(value, res);
187
+ await this.handleHttpResponseMessage(value, res);
199
188
  }
200
189
  else if ((0, utils_1.instanceOfIHttpActionResult)(value)) {
201
- const httpResponseMessage = yield value.executeAsync();
202
- yield this.handleHttpResponseMessage(httpResponseMessage, res);
190
+ const httpResponseMessage = await value.executeAsync();
191
+ await this.handleHttpResponseMessage(httpResponseMessage, res);
203
192
  }
204
193
  else if (value instanceof Function) {
205
194
  value();
@@ -214,36 +203,32 @@ class InversifyExpressServer {
214
203
  catch (err) {
215
204
  next(err);
216
205
  }
217
- });
206
+ };
218
207
  }
219
208
  _getHttpContext(req) {
220
209
  return Reflect.getMetadata(constants_1.METADATA_KEY.httpContext, req);
221
210
  }
222
- _createHttpContext(req, res, next) {
223
- return __awaiter(this, void 0, void 0, function* () {
224
- const principal = yield this._getCurrentUser(req, res, next);
225
- return {
226
- // We use a childContainer for each request so we can be
227
- // sure that the binding is unique for each HTTP request
228
- container: this._container.createChild(),
229
- request: req,
230
- response: res,
231
- user: principal,
232
- };
233
- });
211
+ async _createHttpContext(req, res, next) {
212
+ const principal = await this._getCurrentUser(req, res, next);
213
+ return {
214
+ // We use a childContainer for each request so we can be
215
+ // sure that the binding is unique for each HTTP request
216
+ container: this._container.createChild(),
217
+ request: req,
218
+ response: res,
219
+ user: principal,
220
+ };
234
221
  }
235
- _getCurrentUser(req, res, next) {
236
- return __awaiter(this, void 0, void 0, function* () {
237
- if (this._AuthProvider !== undefined) {
238
- const authProvider = this._container.get(constants_1.TYPE.AuthProvider);
239
- return authProvider.getUser(req, res, next);
240
- }
241
- return Promise.resolve({
242
- details: null,
243
- isAuthenticated: () => Promise.resolve(false),
244
- isInRole: (_role) => Promise.resolve(false),
245
- isResourceOwner: (_resourceId) => Promise.resolve(false),
246
- });
222
+ async _getCurrentUser(req, res, next) {
223
+ if (this._AuthProvider !== undefined) {
224
+ const authProvider = this._container.get(constants_1.TYPE.AuthProvider);
225
+ return authProvider.getUser(req, res, next);
226
+ }
227
+ return Promise.resolve({
228
+ details: null,
229
+ isAuthenticated: () => Promise.resolve(false),
230
+ isInRole: (_role) => Promise.resolve(false),
231
+ isResourceOwner: (_resourceId) => Promise.resolve(false),
247
232
  });
248
233
  }
249
234
  extractParameters(req, res, next, params) {
@@ -286,7 +271,7 @@ class InversifyExpressServer {
286
271
  return args;
287
272
  }
288
273
  getParam(source, paramType, injectRoot, name) {
289
- const key = paramType === "headers" ? name === null || name === void 0 ? void 0 : name.toLowerCase() : name;
274
+ const key = paramType === "headers" ? name?.toLowerCase() : name;
290
275
  const param = source[paramType];
291
276
  if (injectRoot) {
292
277
  return param;
@@ -40,7 +40,7 @@ function getControllerParameterMetadata(constructor) {
40
40
  const parameterMetadata = Reflect.getOwnMetadata(constants_1.METADATA_KEY.controllerParameter, constructor);
41
41
  const genericMetadata = Reflect.getMetadata(constants_1.METADATA_KEY.controllerParameter, Reflect.getPrototypeOf(constructor));
42
42
  if (genericMetadata !== undefined && parameterMetadata !== undefined) {
43
- return Object.assign(Object.assign({}, parameterMetadata), genericMetadata);
43
+ return { ...parameterMetadata, ...genericMetadata };
44
44
  }
45
45
  if (genericMetadata !== undefined) {
46
46
  return genericMetadata;
@@ -18,4 +18,5 @@ exports.ServerEnvironment = exports.AppExpress = void 0;
18
18
  __exportStar(require("./express-utils"), exports);
19
19
  var application_express_1 = require("./application-express");
20
20
  Object.defineProperty(exports, "AppExpress", { enumerable: true, get: function () { return application_express_1.AppExpress; } });
21
- Object.defineProperty(exports, "ServerEnvironment", { enumerable: true, get: function () { return application_express_1.ServerEnvironment; } });
21
+ var application_express_types_1 = require("./application-express.types");
22
+ Object.defineProperty(exports, "ServerEnvironment", { enumerable: true, get: function () { return application_express_types_1.ServerEnvironment; } });
@@ -18,37 +18,30 @@
18
18
  * @export
19
19
  * @abstract
20
20
  */
21
- declare abstract class ApplicationBase {
21
+ export declare abstract class ApplicationBase {
22
22
  /**
23
- * Method to configure services that should be initialized
24
- * before the server starts. It must be implemented by the
25
- * extending class to set up necessary services or configurations.
26
- * Can return a Promise for async configuration.
23
+ * Implement this method to set up required services or configurations before
24
+ * the server starts. This is essential for initializing dependencies or settings
25
+ * necessary for server operation. Supports asynchronous setup with a Promise.
27
26
  *
28
27
  * @abstract
29
28
  * @returns {void | Promise<void>}
30
29
  */
31
30
  protected abstract configureServices(): void | Promise<void>;
32
31
  /**
33
- * Method to configure services or actions that should be executed
34
- * after the server starts. It allows the extending class to perform
35
- * any necessary operations once the server is up and running.
36
- * Can return a Promise for async execution.
32
+ * Implement this method to execute actions or configurations after the server
33
+ * has started. Use this for operations that need to run once the server is
34
+ * operational. Supports asynchronous execution with a Promise.
37
35
  *
38
36
  * @abstract
39
37
  * @returns {void | Promise<void>}
40
38
  */
41
39
  protected abstract postServerInitialization(): void | Promise<void>;
42
40
  /**
43
- * Method to perform any necessary actions or cleanup after the server
44
- * is shutting down. This might include closing database connections,
45
- * stopping background tasks, or other cleanup activities. It provides
46
- * a clean exit point for the server.
47
- * Can return a Promise for async cleanup.
48
- *
49
- * @abstract
50
- * @returns {void | Promise<void>}
41
+ * Implement this method to handle cleanup and final actions when the server
42
+ * is shutting down. Ideal for closing resources, stopping tasks, or other
43
+ * cleanup procedures to ensure a graceful server shutdown. Supports asynchronous
44
+ * cleanup with a Promise.
51
45
  */
52
46
  protected abstract serverShutdown(): void | Promise<void>;
53
47
  }
54
- export { ApplicationBase };
@@ -1,37 +1,26 @@
1
- import express from "express";
2
- import { Container } from "inversify";
3
1
  import { IApplicationMessageToConsole, RenderTemplateOptions } from "@expressots/core";
4
- import { IApplicationExpress } from "./application-express.interface";
5
- import { ApplicationBase } from "./application-base";
6
- /**
7
- * ExpressHandler Type
8
- *
9
- * The ExpressHandler type is a union type that represents various types of Express middleware functions.
10
- * It can be one of the following types:
11
- * - express.ErrorRequestHandler: Handles errors in the middleware pipeline.
12
- * - express.RequestParamHandler: Handles parameters in the middleware pipeline.
13
- * - express.RequestHandler: General request handler.
14
- * - undefined: Represents the absence of a handler.
15
- */
16
- type ExpressHandler = express.ErrorRequestHandler | express.RequestParamHandler | express.RequestHandler | undefined;
17
- /**
18
- * Enum representing possible server environments.
19
- */
20
- declare enum ServerEnvironment {
21
- Development = "development",
22
- Production = "production"
23
- }
2
+ import { Container } from "inversify";
3
+ import { ApplicationBase } from "./application-express.base";
4
+ import { IWebServer, ServerEnvironment } from "./application-express.types";
24
5
  /**
25
- * The Application class provides a way to configure and manage an Express application.
26
- * @provide Application
6
+ * The AppExpress class provides methods for configuring and running an Express application.
7
+ * @class AppExpress
8
+ * @implements {IWebServer} - Interface for the WebServer application implementation.
9
+ * @extends {ApplicationBase} - Base class for the application implementation that provides lifecycle hooks.
10
+ * @method configure - Configures the InversifyJS container.
11
+ * @method listen - Start listening on the given port and environment.
12
+ * @method setGlobalRoutePrefix - Sets the global route prefix for the application.
13
+ * @method setEngine - Configures the application's view engine based on the provided configuration options.
14
+ * @method isDevelopment - Verifies if the current environment is development.
27
15
  */
28
- declare class ApplicationExpress extends ApplicationBase implements IApplicationExpress {
16
+ declare class AppExpress extends ApplicationBase implements IWebServer {
29
17
  private app;
30
18
  private port;
31
19
  private environment;
32
20
  private container;
33
- private middlewares;
34
21
  private globalPrefix;
22
+ private middlewares;
23
+ private console;
35
24
  protected configureServices(): void | Promise<void>;
36
25
  protected postServerInitialization(): void | Promise<void>;
37
26
  protected serverShutdown(): void | Promise<void>;
@@ -39,6 +28,11 @@ declare class ApplicationExpress extends ApplicationBase implements IApplication
39
28
  * Handles process exit by calling serverShutdown and then exiting the process.
40
29
  */
41
30
  private handleExit;
31
+ /**
32
+ * Configures the InversifyJS container.
33
+ * @param container - The InversifyJS container.
34
+ */
35
+ configure(container: Container): Promise<void>;
42
36
  /**
43
37
  * Configures the Express application with the provided middleware entries.
44
38
  * @param app - The Express application instance.
@@ -52,13 +46,6 @@ declare class ApplicationExpress extends ApplicationBase implements IApplication
52
46
  * @returns The configured Application instance.
53
47
  */
54
48
  private init;
55
- /**
56
- * Create and configure the Express application.
57
- * @param container - The InversifyJS container.
58
- * @param middlewares - An array of Express middlewares to be applied.
59
- * @returns The configured Application instance.
60
- */
61
- create(container: Container, middlewares?: Array<ExpressHandler>): Promise<ApplicationExpress>;
62
49
  /**
63
50
  * Start listening on the given port and environment.
64
51
  * @param port - The port number to listen on.
@@ -94,12 +81,5 @@ declare class ApplicationExpress extends ApplicationBase implements IApplication
94
81
  * @returns A boolean value indicating whether the current environment is development or not.
95
82
  */
96
83
  protected isDevelopment(): boolean;
97
- /**
98
- * Verifies if the current environment is production.
99
- *
100
- * @returns A boolean value indicating whether the current environment is production or not.
101
- *
102
- */
103
- get ExpressApp(): express.Application;
104
84
  }
105
- export { ApplicationExpress as AppExpress, ServerEnvironment };
85
+ export { AppExpress };
@@ -1,17 +1,16 @@
1
1
  import { IApplicationMessageToConsole, RenderTemplateOptions } from "@expressots/core";
2
- import { ServerEnvironment } from "./application-express";
2
+ import { ServerEnvironment } from "./application-express.types";
3
3
  /**
4
- * Interface representing the Application class for Expressjs
5
- * @interface IApplicationExpress
4
+ * Public Interface for the WebServer application.
6
5
  */
7
- interface IApplicationExpress {
6
+ export interface IWebServerPublic {
8
7
  /**
9
8
  * Start listening on the given port and environment.
10
9
  * @param port - The port number to listen on.
11
10
  * @param environment - The server environment.
12
11
  * @param consoleMessage - Optional message to display in the console.
13
12
  */
14
- listen(port: number, environment: ServerEnvironment, consoleMessage?: IApplicationMessageToConsole): Promise<void> | void;
13
+ listen(port: number, environment: ServerEnvironment, consoleMessage?: IApplicationMessageToConsole): Promise<void>;
15
14
  /**
16
15
  * Configures the application's view engine based on the provided configuration options.
17
16
  *
@@ -25,4 +24,3 @@ interface IApplicationExpress {
25
24
  */
26
25
  setEngine<T extends RenderTemplateOptions>(options: T): void;
27
26
  }
28
- export { IApplicationExpress };
@@ -0,0 +1,62 @@
1
+ import express, { Request, Response, NextFunction } from "express";
2
+ import { IApplicationMessageToConsole, RenderTemplateOptions } from "@expressots/core";
3
+ import { Container } from "inversify";
4
+ /**
5
+ * Interface for the WebServer application implementation.
6
+ */
7
+ export interface IWebServer {
8
+ configure(container: Container): Promise<void>;
9
+ listen(port: number, environment: ServerEnvironment, consoleMessage?: IApplicationMessageToConsole): Promise<void>;
10
+ setEngine<T extends RenderTemplateOptions>(options: T): void;
11
+ }
12
+ /**
13
+ * Constructor type for IWebServer.
14
+ */
15
+ export interface IWebServerConstructor<T extends IWebServer> {
16
+ new (): T;
17
+ }
18
+ /**
19
+ * ExpressHandler Type
20
+ *
21
+ * The ExpressHandler type is a union type that represents various types of Express middleware functions.
22
+ * It can be one of the following types:
23
+ * - express.ErrorRequestHandler: Handles errors in the middleware pipeline.
24
+ * - express.RequestParamHandler: Handles parameters in the middleware pipeline.
25
+ * - express.RequestHandler: General request handler.
26
+ * - undefined: Represents the absence of a handler.
27
+ */
28
+ export type ExpressHandler = express.ErrorRequestHandler | express.RequestParamHandler | express.RequestHandler | undefined;
29
+ /**
30
+ * MiddlewareConfig Interface
31
+ *
32
+ * The MiddlewareConfig interface specifies the structure for middleware configuration objects.
33
+ * - path: Optional. The route path for which the middleware is configured.
34
+ * - middlewares: An array of ExpressHandler types that make up the middleware pipeline for the route specified by 'path'.
35
+ */
36
+ export type MiddlewareConfig = {
37
+ path?: string;
38
+ middlewares: Array<ExpressHandler>;
39
+ };
40
+ /**
41
+ * Expresso middleware interface.
42
+ */
43
+ interface IExpressoMiddleware {
44
+ use(req: Request, res: Response, next: NextFunction): Promise<void> | void;
45
+ }
46
+ /**
47
+ * Abstract class for creating custom Expresso middleware.
48
+ * Custom middleware classes should extend this class and implement the use method.
49
+ *
50
+ */
51
+ export declare abstract class ExpressoMiddleware implements IExpressoMiddleware {
52
+ get name(): string;
53
+ abstract use(req: Request, res: Response, next: NextFunction): Promise<void> | void;
54
+ }
55
+ /**
56
+ * Enum representing possible server environments.
57
+ */
58
+ export declare enum ServerEnvironment {
59
+ Development = "development",
60
+ Production = "production"
61
+ }
62
+ export {};
@@ -1,7 +1,7 @@
1
1
  import "reflect-metadata";
2
2
  import { PARAMETER_TYPE, HTTP_VERBS_ENUM } from "./constants";
3
3
  import type { Controller, HandlerDecorator, Middleware } from "./interfaces";
4
- export declare const injectHttpContext: (target: import("inversify/lib/annotation/decorator_utils").DecoratorTarget<unknown>, targetKey?: string | symbol, indexOrPropertyDescriptor?: number | TypedPropertyDescriptor<any>) => void;
4
+ export declare const injectHttpContext: (target: import("inversify/lib/annotation/decorator_utils").DecoratorTarget<unknown>, targetKey?: string | symbol, indexOrPropertyDescriptor?: number | TypedPropertyDescriptor<unknown>) => void;
5
5
  export declare function controller(path: string, ...middleware: Array<Middleware>): (target: NewableFunction) => void;
6
6
  export declare function all(path: string, ...middleware: Array<Middleware>): HandlerDecorator;
7
7
  export declare function Get(path: string, ...middleware: Array<Middleware>): HandlerDecorator;
@@ -1,3 +1,4 @@
1
1
  export * from "./express-utils";
2
- export { AppExpress, ServerEnvironment } from "./application-express";
3
- export { IApplicationExpress } from "./application-express.interface";
2
+ export { AppExpress } from "./application-express";
3
+ export { IWebServerPublic } from "./application-express.interface";
4
+ export { IWebServer, IWebServerConstructor, ServerEnvironment } from "./application-express.types";
package/lib/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressots/adapter-express",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Expressots - modern, fast, lightweight nodejs web framework (@adapter-express)",
5
5
  "author": "",
6
6
  "main": "./lib/cjs/index.js",
@@ -56,35 +56,36 @@
56
56
  "build": "npm run clean && npm run build:cjs && npm run copy",
57
57
  "build:cjs": "tsc -p tsconfig.cjs.json",
58
58
  "release": "release-it",
59
+ "prepublish": "npm run build && npm pack",
59
60
  "test": "jest",
60
61
  "format": "prettier --write \"src/**/*.ts\" --cache",
61
62
  "lint": "eslint \"src/**/*.ts\"",
62
63
  "lint:fix": "eslint \"src/**/*.ts\" --fix"
63
64
  },
64
65
  "dependencies": {
65
- "dotenv": "^16.0.3",
66
- "inversify": "^6.0.1",
67
- "inversify-binding-decorators": "^4.0.0",
68
- "jest": "^29.5.0",
69
- "reflect-metadata": "^0.1.13"
66
+ "dotenv": "16.4.5",
67
+ "inversify": "6.0.2",
68
+ "inversify-binding-decorators": "4.0.0",
69
+ "jest": "29.5.0",
70
+ "reflect-metadata": "0.2.2"
70
71
  },
71
72
  "devDependencies": {
72
73
  "@commitlint/cli": "^18.0.0",
73
- "@commitlint/config-conventional": "^17.7.0",
74
- "@expressots/core": "^2.2.0",
75
- "@release-it/conventional-changelog": "^7.0.1",
76
- "@types/express": "^4.17.17",
77
- "@types/jest": "^29.5.0",
78
- "@types/node": "^20.4.9",
79
- "@typescript-eslint/eslint-plugin": "^6.6.0",
80
- "@typescript-eslint/parser": "^6.6.0",
81
- "eslint": "^8.48.0",
82
- "eslint-config-prettier": "^9.0.0",
83
- "husky": "^8.0.3",
84
- "prettier": "^3.0.3",
85
- "release-it": "^16.1.5",
86
- "ts-jest": "^29.0.5",
87
- "typescript": "^5.2.2"
74
+ "@commitlint/config-conventional": "17.7.0",
75
+ "@expressots/core": "latest",
76
+ "@release-it/conventional-changelog": "7.0.1",
77
+ "@types/express": "4.17.21",
78
+ "@types/jest": "29.5.0",
79
+ "@types/node": "20.4.9",
80
+ "@typescript-eslint/eslint-plugin": "6.6.0",
81
+ "@typescript-eslint/parser": "6.6.0",
82
+ "eslint": "8.48.0",
83
+ "eslint-config-prettier": "9.0.0",
84
+ "husky": "8.0.3",
85
+ "prettier": "3.0.3",
86
+ "release-it": "16.1.5",
87
+ "ts-jest": "29.0.5",
88
+ "typescript": "5.2.2"
88
89
  },
89
90
  "release-it": {
90
91
  "git": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressots/adapter-express",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Expressots - modern, fast, lightweight nodejs web framework (@adapter-express)",
5
5
  "author": "",
6
6
  "main": "./lib/cjs/index.js",
@@ -56,35 +56,36 @@
56
56
  "build": "npm run clean && npm run build:cjs && npm run copy",
57
57
  "build:cjs": "tsc -p tsconfig.cjs.json",
58
58
  "release": "release-it",
59
+ "prepublish": "npm run build && npm pack",
59
60
  "test": "jest",
60
61
  "format": "prettier --write \"src/**/*.ts\" --cache",
61
62
  "lint": "eslint \"src/**/*.ts\"",
62
63
  "lint:fix": "eslint \"src/**/*.ts\" --fix"
63
64
  },
64
65
  "dependencies": {
65
- "dotenv": "^16.0.3",
66
- "inversify": "^6.0.1",
67
- "inversify-binding-decorators": "^4.0.0",
68
- "jest": "^29.5.0",
69
- "reflect-metadata": "^0.1.13"
66
+ "dotenv": "16.4.5",
67
+ "inversify": "6.0.2",
68
+ "inversify-binding-decorators": "4.0.0",
69
+ "jest": "29.5.0",
70
+ "reflect-metadata": "0.2.2"
70
71
  },
71
72
  "devDependencies": {
72
73
  "@commitlint/cli": "^18.0.0",
73
- "@commitlint/config-conventional": "^17.7.0",
74
- "@expressots/core": "^2.2.0",
75
- "@release-it/conventional-changelog": "^7.0.1",
76
- "@types/express": "^4.17.17",
77
- "@types/jest": "^29.5.0",
78
- "@types/node": "^20.4.9",
79
- "@typescript-eslint/eslint-plugin": "^6.6.0",
80
- "@typescript-eslint/parser": "^6.6.0",
81
- "eslint": "^8.48.0",
82
- "eslint-config-prettier": "^9.0.0",
83
- "husky": "^8.0.3",
84
- "prettier": "^3.0.3",
85
- "release-it": "^16.1.5",
86
- "ts-jest": "^29.0.5",
87
- "typescript": "^5.2.2"
74
+ "@commitlint/config-conventional": "17.7.0",
75
+ "@expressots/core": "latest",
76
+ "@release-it/conventional-changelog": "7.0.1",
77
+ "@types/express": "4.17.21",
78
+ "@types/jest": "29.5.0",
79
+ "@types/node": "20.4.9",
80
+ "@typescript-eslint/eslint-plugin": "6.6.0",
81
+ "@typescript-eslint/parser": "6.6.0",
82
+ "eslint": "8.48.0",
83
+ "eslint-config-prettier": "9.0.0",
84
+ "husky": "8.0.3",
85
+ "prettier": "3.0.3",
86
+ "release-it": "16.1.5",
87
+ "ts-jest": "29.0.5",
88
+ "typescript": "5.2.2"
88
89
  },
89
90
  "release-it": {
90
91
  "git": {