@ticatec/common-express-server 0.3.0 → 0.3.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.
Files changed (43) hide show
  1. package/lib/AppConf.d.ts +31 -0
  2. package/lib/AppConf.js +57 -0
  3. package/lib/AppConf.js.map +1 -0
  4. package/lib/BaseServer.d.ts +125 -0
  5. package/lib/BaseServer.js +155 -0
  6. package/lib/BaseServer.js.map +1 -0
  7. package/lib/CommonProcessor.d.ts +49 -0
  8. package/lib/CommonProcessor.js +99 -0
  9. package/lib/CommonProcessor.js.map +1 -0
  10. package/lib/CommonRouterHelper.d.ts +64 -0
  11. package/lib/CommonRouterHelper.js +134 -0
  12. package/lib/CommonRouterHelper.js.map +1 -0
  13. package/lib/CommonRoutes.d.ts +33 -0
  14. package/lib/CommonRoutes.js +57 -0
  15. package/lib/CommonRoutes.js.map +1 -0
  16. package/lib/LoggedUser.d.ts +33 -0
  17. package/lib/LoggedUser.js +3 -0
  18. package/lib/LoggedUser.js.map +1 -0
  19. package/lib/ProcessorManager.d.ts +14 -0
  20. package/lib/ProcessorManager.js +30 -0
  21. package/lib/ProcessorManager.js.map +1 -0
  22. package/lib/common/AdminBaseController.d.ts +30 -0
  23. package/lib/common/AdminBaseController.js +41 -0
  24. package/lib/common/AdminBaseController.js.map +1 -0
  25. package/lib/common/AdminSearchController.d.ts +13 -0
  26. package/lib/common/AdminSearchController.js +26 -0
  27. package/lib/common/AdminSearchController.js.map +1 -0
  28. package/lib/common/BaseController.d.ts +28 -0
  29. package/lib/common/BaseController.js +35 -0
  30. package/lib/common/BaseController.js.map +1 -0
  31. package/lib/common/CommonController.d.ts +96 -0
  32. package/lib/common/CommonController.js +129 -0
  33. package/lib/common/CommonController.js.map +1 -0
  34. package/lib/common/TenantBaseController.d.ts +30 -0
  35. package/lib/common/TenantBaseController.js +41 -0
  36. package/lib/common/TenantBaseController.js.map +1 -0
  37. package/lib/common/TenantSearchController.d.ts +13 -0
  38. package/lib/common/TenantSearchController.js +27 -0
  39. package/lib/common/TenantSearchController.js.map +1 -0
  40. package/lib/index.d.ts +14 -0
  41. package/lib/index.js +30 -0
  42. package/lib/index.js.map +1 -0
  43. package/package.json +10 -10
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Application configuration singleton class
3
+ */
4
+ export default class AppConf {
5
+ /** Configuration object */
6
+ private readonly conf;
7
+ /** Singleton instance */
8
+ static instance: AppConf;
9
+ /**
10
+ * Private constructor for singleton pattern
11
+ * @param conf Configuration object
12
+ */
13
+ private constructor();
14
+ /**
15
+ * Gets the singleton instance
16
+ * @returns AppConf instance or null if not initialized
17
+ */
18
+ static getInstance(): AppConf;
19
+ /**
20
+ * Initializes the configuration singleton
21
+ * @param config Configuration object
22
+ * @returns AppConf instance
23
+ */
24
+ static init(config: any): AppConf;
25
+ /**
26
+ * Gets configuration value by key (supports dot notation)
27
+ * @param key Configuration key (can use dot notation like 'server.port')
28
+ * @returns Configuration value or undefined if not found
29
+ */
30
+ get(key: string): any;
31
+ }
package/lib/AppConf.js ADDED
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Application configuration singleton class
5
+ */
6
+ class AppConf {
7
+ /**
8
+ * Private constructor for singleton pattern
9
+ * @param conf Configuration object
10
+ */
11
+ constructor(conf) {
12
+ this.conf = conf;
13
+ }
14
+ /**
15
+ * Gets the singleton instance
16
+ * @returns AppConf instance or null if not initialized
17
+ */
18
+ static getInstance() {
19
+ return AppConf.instance;
20
+ }
21
+ /**
22
+ * Initializes the configuration singleton
23
+ * @param config Configuration object
24
+ * @returns AppConf instance
25
+ */
26
+ static init(config) {
27
+ console.debug('Initializing configuration center', config);
28
+ if (AppConf.instance == null) {
29
+ AppConf.instance = new AppConf(config);
30
+ }
31
+ return AppConf.instance;
32
+ }
33
+ /**
34
+ * Gets configuration value by key (supports dot notation)
35
+ * @param key Configuration key (can use dot notation like 'server.port')
36
+ * @returns Configuration value or undefined if not found
37
+ */
38
+ get(key) {
39
+ if (!key)
40
+ return undefined;
41
+ const keys = key.split('.');
42
+ let result = this.conf;
43
+ for (const k of keys) {
44
+ if (result && typeof result === 'object' && k in result) {
45
+ result = result[k];
46
+ }
47
+ else {
48
+ return undefined;
49
+ }
50
+ }
51
+ return result;
52
+ }
53
+ }
54
+ /** Singleton instance */
55
+ AppConf.instance = null;
56
+ exports.default = AppConf;
57
+ //# sourceMappingURL=AppConf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AppConf.js","sourceRoot":"src/","sources":["AppConf.ts"],"names":[],"mappings":";;AAAA;;GAEG;AACH,MAAqB,OAAO;IAOxB;;;OAGG;IACH,YAAoB,IAAS;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,WAAW;QACd,OAAO,OAAO,CAAC,QAAQ,CAAC;IAC5B,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,IAAI,CAAC,MAAW;QACnB,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,MAAM,CAAC,CAAC;QAC3D,IAAI,OAAO,CAAC,QAAQ,IAAI,IAAI,EAAE,CAAC;YAC3B,OAAO,CAAC,QAAQ,GAAG,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;QAC3C,CAAC;QACD,OAAO,OAAO,CAAC,QAAQ,CAAC;IAC5B,CAAC;IAED;;;;OAIG;IACH,GAAG,CAAC,GAAW;QACX,IAAI,CAAC,GAAG;YAAE,OAAO,SAAS,CAAC;QAE3B,MAAM,IAAI,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC;QAEvB,KAAK,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;YACnB,IAAI,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,IAAI,MAAM,EAAE,CAAC;gBACtD,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;YACvB,CAAC;iBAAM,CAAC;gBACJ,OAAO,SAAS,CAAC;YACrB,CAAC;QACL,CAAC;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;;AApDD,yBAAyB;AAClB,gBAAQ,GAAY,IAAI,CAAC;kBALf,OAAO"}
@@ -0,0 +1,125 @@
1
+ import { Express } from 'express';
2
+ import CommonRouterHelper from "./CommonRouterHelper";
3
+ import http from "http";
4
+ import { Logger } from "log4js";
5
+ /**
6
+ * Function signature for module loader
7
+ */
8
+ export type moduleLoader = () => Promise<any>;
9
+ /**
10
+ * Abstract base server class providing common functionality for Express servers
11
+ * @template T The type of CommonRouterHelper this server uses
12
+ */
13
+ export default abstract class BaseServer<T extends CommonRouterHelper> {
14
+ /** Logger instance for this server */
15
+ protected logger: Logger;
16
+ /** Router helper instance */
17
+ protected helper: T;
18
+ /** Context root path for the server */
19
+ protected contextRoot: string;
20
+ /**
21
+ * Protected constructor for base server
22
+ * @protected
23
+ */
24
+ protected constructor();
25
+ /**
26
+ * Gets the router helper instance for this server
27
+ * @returns RouterHelper instance
28
+ * @protected
29
+ * @abstract
30
+ */
31
+ protected abstract getHelper(): T;
32
+ /**
33
+ * Loads configuration file
34
+ * @returns Promise that resolves when configuration is loaded
35
+ * @protected
36
+ * @abstract
37
+ */
38
+ protected abstract loadConfigFile(): Promise<void>;
39
+ /**
40
+ * Writes the listening port to check.dat file
41
+ * @param port The port number to write
42
+ * @param fileName The file name to write to (default: './check.dat')
43
+ * @protected
44
+ */
45
+ protected writeCheckFile(port: number, fileName?: string): void;
46
+ /**
47
+ * Starts up the server
48
+ * @returns Promise that resolves when server startup is complete
49
+ */
50
+ startup(): Promise<void>;
51
+ /**
52
+ * Interceptor function called after web server is created
53
+ * @param server The HTTP server instance
54
+ * @returns Promise that resolves when post-creation setup is complete
55
+ * @protected
56
+ */
57
+ protected postServerCreated(server: http.Server): Promise<void>;
58
+ /**
59
+ * Gets web configuration
60
+ * @returns Web configuration object
61
+ * @protected
62
+ * @abstract
63
+ */
64
+ protected abstract getWebConf(): any;
65
+ /**
66
+ * Interceptor function called before startup
67
+ * @returns Promise that resolves when pre-startup setup is complete
68
+ * @protected
69
+ */
70
+ protected beforeStart(): Promise<void>;
71
+ /**
72
+ * Gets the health check endpoint path
73
+ * @returns The health check path
74
+ * @protected
75
+ */
76
+ protected getHealthCheckPath(): string;
77
+ /**
78
+ * Adds health check endpoint to the Express app
79
+ * @param app Express application instance
80
+ * @protected
81
+ */
82
+ protected addHealthCheck(app: Express): void;
83
+ /**
84
+ * Starts the web server with given configuration
85
+ * @param webConf Web server configuration
86
+ * @returns Promise that resolves to the HTTP server instance
87
+ * @protected
88
+ */
89
+ protected startWebServer(webConf: any): Promise<unknown>;
90
+ /**
91
+ * Binds static site resources
92
+ * @param app Express application instance
93
+ * @returns Promise that resolves when static binding is complete
94
+ * @protected
95
+ */
96
+ protected bindStaticSite(app: Express): Promise<void>;
97
+ /**
98
+ * Initializes Express application
99
+ * @param app Express application instance
100
+ * @protected
101
+ */
102
+ protected setupExpress(app: Express): void;
103
+ /**
104
+ * Binds a route to the Express application
105
+ * @param app Express application instance
106
+ * @param path The route path
107
+ * @param loader Module loader function that returns the route class
108
+ * @returns Promise that resolves when route binding is complete
109
+ * @protected
110
+ */
111
+ protected bindRoutes(app: Express, path: string, loader: moduleLoader): Promise<void>;
112
+ /**
113
+ * Sets up routes for the application
114
+ * @param app Express application instance
115
+ * @returns Promise that resolves when all routes are set up
116
+ * @protected
117
+ * @abstract
118
+ */
119
+ protected abstract setupRoutes(app: Express): Promise<void>;
120
+ /**
121
+ * Static method to start a server instance
122
+ * @param server The server instance to start
123
+ */
124
+ static startup(server: BaseServer<any>): void;
125
+ }
@@ -0,0 +1,155 @@
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 express_1 = __importDefault(require("express"));
7
+ const express_exception_1 = require("@ticatec/express-exception");
8
+ const fs_1 = __importDefault(require("fs"));
9
+ /**
10
+ * Abstract base server class providing common functionality for Express servers
11
+ * @template T The type of CommonRouterHelper this server uses
12
+ */
13
+ class BaseServer {
14
+ /**
15
+ * Protected constructor for base server
16
+ * @protected
17
+ */
18
+ constructor() {
19
+ }
20
+ /**
21
+ * Writes the listening port to check.dat file
22
+ * @param port The port number to write
23
+ * @param fileName The file name to write to (default: './check.dat')
24
+ * @protected
25
+ */
26
+ writeCheckFile(port, fileName = './check.dat') {
27
+ try {
28
+ this.logger.debug('Port', port);
29
+ fs_1.default.writeFileSync(fileName, `${port}`);
30
+ }
31
+ catch (err) {
32
+ this.logger.error('Error writing port file', err);
33
+ }
34
+ }
35
+ /**
36
+ * Starts up the server
37
+ * @returns Promise that resolves when server startup is complete
38
+ */
39
+ async startup() {
40
+ await this.loadConfigFile();
41
+ try {
42
+ await this.beforeStart();
43
+ this.helper = this.getHelper();
44
+ let webConf = this.getWebConf();
45
+ this.writeCheckFile(webConf.port);
46
+ this.contextRoot = webConf.contextRoot;
47
+ await this.startWebServer(webConf);
48
+ }
49
+ catch (err) {
50
+ this.logger.error('Startup failed, reason:', err);
51
+ }
52
+ }
53
+ /**
54
+ * Interceptor function called after web server is created
55
+ * @param server The HTTP server instance
56
+ * @returns Promise that resolves when post-creation setup is complete
57
+ * @protected
58
+ */
59
+ async postServerCreated(server) {
60
+ }
61
+ /**
62
+ * Interceptor function called before startup
63
+ * @returns Promise that resolves when pre-startup setup is complete
64
+ * @protected
65
+ */
66
+ async beforeStart() {
67
+ }
68
+ /**
69
+ * Gets the health check endpoint path
70
+ * @returns The health check path
71
+ * @protected
72
+ */
73
+ getHealthCheckPath() {
74
+ return '/health-check';
75
+ }
76
+ /**
77
+ * Adds health check endpoint to the Express app
78
+ * @param app Express application instance
79
+ * @protected
80
+ */
81
+ addHealthCheck(app) {
82
+ let path = this.getHealthCheckPath();
83
+ this.logger.debug('Loading system health check', path);
84
+ if (path) {
85
+ app.get(path, (req, res) => { res.send(''); });
86
+ }
87
+ }
88
+ /**
89
+ * Starts the web server with given configuration
90
+ * @param webConf Web server configuration
91
+ * @returns Promise that resolves to the HTTP server instance
92
+ * @protected
93
+ */
94
+ async startWebServer(webConf) {
95
+ let app = (0, express_1.default)();
96
+ app.disable("x-powered-by");
97
+ app.use(this.helper.setNoCache);
98
+ this.addHealthCheck(app);
99
+ this.setupExpress(app);
100
+ await this.bindStaticSite(app);
101
+ await this.setupRoutes(app);
102
+ app.use(this.helper.actionNotFound());
103
+ app.use((err, req, res, next) => {
104
+ this.logger.debug("application error: ", err);
105
+ (0, express_exception_1.handleError)(err, req, res);
106
+ });
107
+ return new Promise(resolve => {
108
+ let server = app.listen(webConf.port, webConf.ip, () => {
109
+ this.logger.info(`Web service started successfully, listening on IP: ${webConf.ip}, port: ${webConf.port}`);
110
+ this.postServerCreated(server);
111
+ resolve(server);
112
+ });
113
+ });
114
+ }
115
+ /**
116
+ * Binds static site resources
117
+ * @param app Express application instance
118
+ * @returns Promise that resolves when static binding is complete
119
+ * @protected
120
+ */
121
+ async bindStaticSite(app) {
122
+ }
123
+ /**
124
+ * Initializes Express application
125
+ * @param app Express application instance
126
+ * @protected
127
+ */
128
+ setupExpress(app) {
129
+ }
130
+ /**
131
+ * Binds a route to the Express application
132
+ * @param app Express application instance
133
+ * @param path The route path
134
+ * @param loader Module loader function that returns the route class
135
+ * @returns Promise that resolves when route binding is complete
136
+ * @protected
137
+ */
138
+ async bindRoutes(app, path, loader) {
139
+ let clazz = (await loader()).default;
140
+ let router = new clazz(this.helper);
141
+ router.bindRouter(app, `${this.contextRoot}${path}`);
142
+ }
143
+ /**
144
+ * Static method to start a server instance
145
+ * @param server The server instance to start
146
+ */
147
+ static startup(server) {
148
+ server.startup().then(() => {
149
+ }).catch(ex => {
150
+ console.error('Server startup error', ex);
151
+ });
152
+ }
153
+ }
154
+ exports.default = BaseServer;
155
+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4
+ Running = 1
5
+ }
6
+ export default abstract class CommonProcessor<T> {
7
+ protected logger: log4js.Logger;
8
+ protected interval: number;
9
+ protected processInterval: any;
10
+ private nappingDuration;
11
+ private status;
12
+ private readonly ants;
13
+ /**
14
+ * 构造函数
15
+ * @param interval 检查间隔
16
+ * @param ants 工蚁数量,可以同步执行的线程数量
17
+ * @protected
18
+ */
19
+ protected constructor(interval: number, ants?: number);
20
+ /**
21
+ * 启动
22
+ */
23
+ startup(): void;
24
+ /**
25
+ * 停止
26
+ */
27
+ stop(): void;
28
+ private checkNap;
29
+ /**
30
+ * 开始处理数据
31
+ * @protected
32
+ */
33
+ protected startProcess(): Promise<void>;
34
+ /**
35
+ * 读取待处理的数据
36
+ * @protected
37
+ */
38
+ protected abstract loadToProcessData(): Promise<Array<T>>;
39
+ /**
40
+ * 立即执行
41
+ */
42
+ runImmediately(): void;
43
+ /**
44
+ * 处理单条数据
45
+ * @protected
46
+ * @param item
47
+ */
48
+ protected abstract processItem(item: T): Promise<void>;
49
+ }
@@ -0,0 +1,99 @@
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
+ exports.ProcessStatus = void 0;
7
+ const node_timers_1 = require("node:timers");
8
+ const log4js_1 = __importDefault(require("log4js"));
9
+ var ProcessStatus;
10
+ (function (ProcessStatus) {
11
+ ProcessStatus[ProcessStatus["Napping"] = 0] = "Napping";
12
+ ProcessStatus[ProcessStatus["Running"] = 1] = "Running";
13
+ })(ProcessStatus || (exports.ProcessStatus = ProcessStatus = {}));
14
+ class CommonProcessor {
15
+ /**
16
+ * 构造函数
17
+ * @param interval 检查间隔
18
+ * @param ants 工蚁数量,可以同步执行的线程数量
19
+ * @protected
20
+ */
21
+ constructor(interval, ants = 5) {
22
+ this.logger = log4js_1.default.getLogger(this.constructor.name);
23
+ this.interval = Math.max(Math.round(interval), 5);
24
+ this.ants = ants;
25
+ this.nappingDuration = 0;
26
+ }
27
+ /**
28
+ * 启动
29
+ */
30
+ startup() {
31
+ if (!this.processInterval) {
32
+ this.logger.debug('启动处理器');
33
+ this.nappingDuration = this.interval;
34
+ this.status = ProcessStatus.Napping;
35
+ this.processInterval = setInterval(this.checkNap(), 1000);
36
+ }
37
+ }
38
+ /**
39
+ * 停止
40
+ */
41
+ stop() {
42
+ if (this.processInterval) {
43
+ this.logger.debug('停止处理器');
44
+ (0, node_timers_1.clearInterval)(this.processInterval);
45
+ this.processInterval = null;
46
+ }
47
+ }
48
+ checkNap() {
49
+ return async () => {
50
+ this.nappingDuration++;
51
+ if (this.nappingDuration >= this.interval && this.status == ProcessStatus.Napping) {
52
+ this.status = ProcessStatus.Running;
53
+ try {
54
+ await this.startProcess();
55
+ }
56
+ finally {
57
+ this.status = ProcessStatus.Napping;
58
+ }
59
+ }
60
+ };
61
+ }
62
+ /**
63
+ * 开始处理数据
64
+ * @protected
65
+ */
66
+ async startProcess() {
67
+ let arr = await this.loadToProcessData();
68
+ if (arr.length > 0) {
69
+ this.logger.debug('有待处理的数据,开始处理数据');
70
+ const pool = new Set();
71
+ for (const item of arr) {
72
+ const task = this.processItem(item)
73
+ .catch((ex) => {
74
+ this.logger.error(`执行任务 [${item}] 发生错误:`, ex);
75
+ })
76
+ .finally(() => {
77
+ pool.delete(task);
78
+ });
79
+ pool.add(task);
80
+ if (pool.size >= this.ants) {
81
+ await Promise.race(pool);
82
+ }
83
+ }
84
+ await Promise.all(pool);
85
+ }
86
+ else {
87
+ this.nappingDuration = 0;
88
+ }
89
+ }
90
+ /**
91
+ * 立即执行
92
+ */
93
+ runImmediately() {
94
+ this.logger.debug('立即执行');
95
+ this.nappingDuration = this.interval;
96
+ }
97
+ }
98
+ exports.default = CommonProcessor;
99
+ //# sourceMappingURL=CommonProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CommonProcessor.js","sourceRoot":"src/","sources":["CommonProcessor.ts"],"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5B,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,eAAe,GAAG,CAAC,CAAC;QAC7B,CAAC;IACL,CAAC;IASD;;OAEG;IACH,cAAc;QACV,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC1B,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,QAAQ,CAAC;IACzC,CAAC;CAQJ;AA5GD,kCA4GC"}
@@ -0,0 +1,64 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+ import log4js from "log4js";
3
+ /**
4
+ * Function signature for RESTful API handlers
5
+ */
6
+ export type RestfulFunction = (req: Request) => any;
7
+ /**
8
+ * Function signature for control handlers
9
+ */
10
+ export type ControlFunction = (req: Request, res: Response) => any;
11
+ /**
12
+ * Common router helper class providing middleware and utilities for Express routing
13
+ */
14
+ export default class CommonRouterHelper {
15
+ /** Logger instance for this router helper */
16
+ protected readonly logger: log4js.Logger;
17
+ /**
18
+ * Sets HTTP response header to JSON format
19
+ * @param req Express request object
20
+ * @param res Express response object
21
+ * @param next Express next function
22
+ */
23
+ setJsonHeader(req: Request, res: Response, next: NextFunction): void;
24
+ /**
25
+ * Sets response headers to disable caching
26
+ * @param req Express request object
27
+ * @param res Express response object
28
+ * @param next Express next function
29
+ */
30
+ setNoCache(req: Request, res: Response, next: NextFunction): void;
31
+ /**
32
+ * Invokes a RESTful operation and wraps the result in JSON format for the client
33
+ * @param func The RESTful function to execute
34
+ * @returns Express middleware function
35
+ */
36
+ invokeRestfulAction(func: RestfulFunction): any;
37
+ /**
38
+ * Invokes an asynchronous controller function with error handling
39
+ * @param func The controller function to execute
40
+ * @returns Express middleware function
41
+ */
42
+ invokeController(func: ControlFunction): (req: Request, res: Response) => Promise<void>;
43
+ /**
44
+ * Handles invalid request paths by throwing ActionNotFoundError
45
+ * @returns Express middleware function for handling 404 errors
46
+ */
47
+ actionNotFound(): (req: Request, res: Response, next: NextFunction) => void;
48
+ /**
49
+ * Retrieves user information from request headers
50
+ * @param req Express request object
51
+ * @protected
52
+ */
53
+ protected retrieveUserFormHeader(req: Request): void;
54
+ /**
55
+ * Middleware to retrieve user information from headers
56
+ * @returns Express middleware function
57
+ */
58
+ retrieveUser(): (req: Request, res: Response, next: any) => void;
59
+ /**
60
+ * Middleware to check if user is authenticated
61
+ * @returns Express middleware function that validates user authentication
62
+ */
63
+ checkLoggedUser(): (req: Request, res: Response, next: any) => void;
64
+ }