opticore-api-gateway 1.0.0

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.
@@ -0,0 +1,329 @@
1
+ import { TFeatureRoutes, ICustomContext, TRouteHandler, IMultipleRouterConfig, IMultipleRouteDefinition } from 'opticore-router';
2
+ import * as express from 'express';
3
+ import * as http from 'node:http';
4
+
5
+ interface IServiceConfig {
6
+ name: string;
7
+ url: string;
8
+ healthCheck?: string;
9
+ weight?: number;
10
+ timeout?: number;
11
+ retries?: number;
12
+ }
13
+
14
+ interface ICircuitBreakerConfig {
15
+ failureThreshold: number;
16
+ resetTimeout: number;
17
+ halfOpenMaxAttempts: number;
18
+ }
19
+
20
+ /**
21
+ *
22
+ */
23
+ interface IRouteConfig {
24
+ path: string;
25
+ method: 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
26
+ target: string | string[];
27
+ middlewares?: any[];
28
+ timeout?: number;
29
+ retries?: number;
30
+ circuitBreaker?: ICircuitBreakerConfig;
31
+ serviceName?: string;
32
+ }
33
+
34
+ interface IGatewayConfig {
35
+ port: number;
36
+ services: IServiceConfig[];
37
+ routes: IRouteConfig[];
38
+ globalMiddlewares?: any[];
39
+ loadBalancer?: 'round-robin' | 'weighted' | 'random' | 'least-connections';
40
+ enableLogging?: boolean;
41
+ enableMetrics?: boolean;
42
+ }
43
+
44
+ type TMiddlewareFunction = (req: any, res: any, next: () => void) => void | Promise<void>;
45
+
46
+ declare class APIGateway {
47
+ private config;
48
+ private server;
49
+ private serviceRegistry;
50
+ private loadBalancer;
51
+ private httpClient;
52
+ private middlewareChain;
53
+ private routes;
54
+ private opticoreRoutes;
55
+ private registerRouter;
56
+ constructor(config: IGatewayConfig);
57
+ private initializeServices;
58
+ private initializeGlobalMiddlewares;
59
+ private initializeRoutes;
60
+ private buildOpticoreRoutes;
61
+ private handleGatewayRequest;
62
+ private extractServiceName;
63
+ private rewriteUrl;
64
+ private forwardRequest;
65
+ private sendResponse;
66
+ addRoute(routeConfig: IRouteConfig): void;
67
+ addMiddleware(middleware: TMiddlewareFunction): void;
68
+ registerService(service: any): void;
69
+ getOpticoreRoutes(): TFeatureRoutes[];
70
+ private parseRequestBody;
71
+ getExpressMiddleware(): (req: any, res: any, next: () => void) => void;
72
+ start(): Promise<void>;
73
+ stop(): Promise<void>;
74
+ }
75
+
76
+ interface IServiceInstance extends IServiceConfig {
77
+ healthy: boolean;
78
+ currentConnections: number;
79
+ lastHealthCheck: Date;
80
+ failureCount: number;
81
+ circuitState: 'closed' | 'open' | 'half-open';
82
+ circuitOpenTime?: Date;
83
+ }
84
+
85
+ type TGatewayContext = ICustomContext & {
86
+ serviceUrl?: string;
87
+ serviceInstance?: IServiceInstance;
88
+ gatewayStartTime?: number;
89
+ };
90
+
91
+ declare class GatewayRoute {
92
+ private readonly localLanguage;
93
+ private readonly config;
94
+ private standaloneRouter;
95
+ private collectionRouter;
96
+ private readonly routeHandler;
97
+ private logger;
98
+ /**
99
+ *
100
+ * @param config
101
+ * @param routeHandler
102
+ * @param localLanguage
103
+ */
104
+ constructor(config: IRouteConfig, routeHandler: TRouteHandler, localLanguage: string);
105
+ /**
106
+ * Method for creating a multi-router configuration
107
+ *
108
+ * @param controller
109
+ */
110
+ createMultipleRouterConfig(controller: any): IMultipleRouterConfig<TGatewayContext>;
111
+ /**
112
+ * Method for creating a router collection
113
+ *
114
+ * @param controller
115
+ * @param routes
116
+ */
117
+ createCollectionRouter(controller: any, routes: IMultipleRouterConfig<TGatewayContext>[]): void;
118
+ /**
119
+ * Get the standalone router
120
+ *
121
+ * @param strategy
122
+ * @param options
123
+ */
124
+ getStandaloneRoute(strategy?: string, options?: any): express.Router;
125
+ /**
126
+ * Get the definition of multiple routes
127
+ */
128
+ getMultipleRouteDefinition(): IMultipleRouteDefinition;
129
+ /**
130
+ *
131
+ */
132
+ getConfig(): IRouteConfig;
133
+ /**
134
+ * Utility method for creating an Opticore-compatible route
135
+ *
136
+ * @param path
137
+ * @param handler
138
+ */
139
+ static createOpticoreRouteDefinition(path: string, handler: TRouteHandler): {
140
+ path: string;
141
+ handler: any;
142
+ };
143
+ }
144
+
145
+ declare abstract class BaseMiddleware {
146
+ abstract handle(): TMiddlewareFunction;
147
+ }
148
+ declare class MiddlewareChain {
149
+ private middlewares;
150
+ add(middleware: TMiddlewareFunction): void;
151
+ execute(req: any, res: any, finalHandler: TMiddlewareFunction): Promise<void>;
152
+ getAll(): TMiddlewareFunction[];
153
+ }
154
+
155
+ /**
156
+ *
157
+ */
158
+ declare class ServiceRegistry {
159
+ private services;
160
+ private serviceHealthChecks;
161
+ private circuitBreakers;
162
+ registerService(service: IServiceConfig): void;
163
+ private startHealthCheck;
164
+ getServiceInstances(serviceName: string): IServiceInstance[];
165
+ getHealthyInstances(serviceName: string): IServiceInstance[];
166
+ recordSuccess(serviceName: string, url: string): void;
167
+ recordFailure(serviceName: string, url: string): void;
168
+ deregisterService(serviceName: string, url: string): void;
169
+ getAllServices(): Map<string, IServiceInstance[]>;
170
+ }
171
+
172
+ type TLoadBalancingStrategy = 'round-robin' | 'weighted' | 'random' | 'least-connections';
173
+
174
+ /**
175
+ *
176
+ */
177
+ declare class LoadBalancer {
178
+ private strategy;
179
+ private counters;
180
+ constructor(strategy?: TLoadBalancingStrategy);
181
+ /**
182
+ *
183
+ * @param serviceName
184
+ * @param instances
185
+ */
186
+ selectInstance(serviceName: string, instances: IServiceInstance[]): IServiceInstance | null;
187
+ /**
188
+ *
189
+ * @param serviceName
190
+ * @param instances
191
+ * @private
192
+ */
193
+ private roundRobin;
194
+ /**
195
+ *
196
+ * @param instances
197
+ * @private
198
+ */
199
+ private random;
200
+ /**
201
+ *
202
+ * @param instances
203
+ * @private
204
+ */
205
+ private weighted;
206
+ /**
207
+ *
208
+ * @param instances
209
+ * @private
210
+ */
211
+ private leastConnections;
212
+ /**
213
+ *
214
+ * @param strategy
215
+ */
216
+ setStrategy(strategy: TLoadBalancingStrategy): void;
217
+ }
218
+
219
+ interface IHttpResponse {
220
+ status: number;
221
+ headers: Record<string, string | string[]>;
222
+ body: string;
223
+ }
224
+
225
+ interface IHttpRequestOptions {
226
+ method: string;
227
+ headers?: http.OutgoingHttpHeaders | http.OutgoingHttpHeader[];
228
+ body?: any;
229
+ timeout?: number;
230
+ }
231
+
232
+ declare class HttpClient {
233
+ /**
234
+ *
235
+ * @param url
236
+ * @param options
237
+ */
238
+ request(url: string, options: IHttpRequestOptions): Promise<IHttpResponse>;
239
+ /**
240
+ *
241
+ * @param method
242
+ * @private
243
+ */
244
+ private getDefaultHeaders;
245
+ /**
246
+ *
247
+ * @param req
248
+ * @param body
249
+ * @param headers
250
+ * @private
251
+ */
252
+ private writeRequestBody;
253
+ /**
254
+ *
255
+ * @param headers
256
+ * @private
257
+ */
258
+ private getContentType;
259
+ /**
260
+ *
261
+ * @param url
262
+ * @param headers
263
+ */
264
+ get(url: string, headers?: Record<string, string>): Promise<IHttpResponse>;
265
+ /**
266
+ *
267
+ * @param url
268
+ * @param body
269
+ * @param headers
270
+ */
271
+ post(url: string, body: any, headers?: Record<string, string>): Promise<IHttpResponse>;
272
+ /**
273
+ *
274
+ * @param url
275
+ * @param body
276
+ * @param headers
277
+ */
278
+ put(url: string, body: any, headers?: Record<string, string>): Promise<IHttpResponse>;
279
+ /**
280
+ *
281
+ * @param url
282
+ * @param headers
283
+ */
284
+ delete(url: string, headers?: Record<string, string>): Promise<IHttpResponse>;
285
+ /**
286
+ *
287
+ * @param url
288
+ * @param body
289
+ * @param headers
290
+ */
291
+ patch(url: string, body: any, headers?: Record<string, string>): Promise<IHttpResponse>;
292
+ }
293
+
294
+ declare class AuthMiddleware extends BaseMiddleware {
295
+ private apiKeys;
296
+ constructor(apiKeys?: string[]);
297
+ handle(): TMiddlewareFunction;
298
+ }
299
+
300
+ /**
301
+ *
302
+ */
303
+ declare class RateLimitMiddleware extends BaseMiddleware {
304
+ private requestsPerWindow;
305
+ private windowMs;
306
+ private store;
307
+ constructor(requestsPerWindow?: number, windowMs?: number);
308
+ handle(): TMiddlewareFunction;
309
+ }
310
+
311
+ declare class LoggingMiddleware extends BaseMiddleware {
312
+ private logLevel;
313
+ constructor(logLevel?: 'info' | 'debug' | 'error');
314
+ handle(): TMiddlewareFunction;
315
+ }
316
+
317
+ declare class ValidationMiddleware extends BaseMiddleware {
318
+ private validator;
319
+ private target;
320
+ /**
321
+ * Crée un middleware de validation.
322
+ * @param schema - Le schéma de validation au format opticore-validator.
323
+ * @param target - La partie de la requête à valider (par défaut 'body').
324
+ */
325
+ constructor(schema: any, target?: 'body' | 'query' | 'params' | 'all');
326
+ handle(): TMiddlewareFunction;
327
+ }
328
+
329
+ export { APIGateway, AuthMiddleware, BaseMiddleware, GatewayRoute, HttpClient, type ICircuitBreakerConfig, type IGatewayConfig, type IRouteConfig, type IServiceConfig, LoadBalancer, LoggingMiddleware, MiddlewareChain, RateLimitMiddleware, ServiceRegistry, type TLoadBalancingStrategy, type TMiddlewareFunction, ValidationMiddleware };
@@ -0,0 +1,329 @@
1
+ import { TFeatureRoutes, ICustomContext, TRouteHandler, IMultipleRouterConfig, IMultipleRouteDefinition } from 'opticore-router';
2
+ import * as express from 'express';
3
+ import * as http from 'node:http';
4
+
5
+ interface IServiceConfig {
6
+ name: string;
7
+ url: string;
8
+ healthCheck?: string;
9
+ weight?: number;
10
+ timeout?: number;
11
+ retries?: number;
12
+ }
13
+
14
+ interface ICircuitBreakerConfig {
15
+ failureThreshold: number;
16
+ resetTimeout: number;
17
+ halfOpenMaxAttempts: number;
18
+ }
19
+
20
+ /**
21
+ *
22
+ */
23
+ interface IRouteConfig {
24
+ path: string;
25
+ method: 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
26
+ target: string | string[];
27
+ middlewares?: any[];
28
+ timeout?: number;
29
+ retries?: number;
30
+ circuitBreaker?: ICircuitBreakerConfig;
31
+ serviceName?: string;
32
+ }
33
+
34
+ interface IGatewayConfig {
35
+ port: number;
36
+ services: IServiceConfig[];
37
+ routes: IRouteConfig[];
38
+ globalMiddlewares?: any[];
39
+ loadBalancer?: 'round-robin' | 'weighted' | 'random' | 'least-connections';
40
+ enableLogging?: boolean;
41
+ enableMetrics?: boolean;
42
+ }
43
+
44
+ type TMiddlewareFunction = (req: any, res: any, next: () => void) => void | Promise<void>;
45
+
46
+ declare class APIGateway {
47
+ private config;
48
+ private server;
49
+ private serviceRegistry;
50
+ private loadBalancer;
51
+ private httpClient;
52
+ private middlewareChain;
53
+ private routes;
54
+ private opticoreRoutes;
55
+ private registerRouter;
56
+ constructor(config: IGatewayConfig);
57
+ private initializeServices;
58
+ private initializeGlobalMiddlewares;
59
+ private initializeRoutes;
60
+ private buildOpticoreRoutes;
61
+ private handleGatewayRequest;
62
+ private extractServiceName;
63
+ private rewriteUrl;
64
+ private forwardRequest;
65
+ private sendResponse;
66
+ addRoute(routeConfig: IRouteConfig): void;
67
+ addMiddleware(middleware: TMiddlewareFunction): void;
68
+ registerService(service: any): void;
69
+ getOpticoreRoutes(): TFeatureRoutes[];
70
+ private parseRequestBody;
71
+ getExpressMiddleware(): (req: any, res: any, next: () => void) => void;
72
+ start(): Promise<void>;
73
+ stop(): Promise<void>;
74
+ }
75
+
76
+ interface IServiceInstance extends IServiceConfig {
77
+ healthy: boolean;
78
+ currentConnections: number;
79
+ lastHealthCheck: Date;
80
+ failureCount: number;
81
+ circuitState: 'closed' | 'open' | 'half-open';
82
+ circuitOpenTime?: Date;
83
+ }
84
+
85
+ type TGatewayContext = ICustomContext & {
86
+ serviceUrl?: string;
87
+ serviceInstance?: IServiceInstance;
88
+ gatewayStartTime?: number;
89
+ };
90
+
91
+ declare class GatewayRoute {
92
+ private readonly localLanguage;
93
+ private readonly config;
94
+ private standaloneRouter;
95
+ private collectionRouter;
96
+ private readonly routeHandler;
97
+ private logger;
98
+ /**
99
+ *
100
+ * @param config
101
+ * @param routeHandler
102
+ * @param localLanguage
103
+ */
104
+ constructor(config: IRouteConfig, routeHandler: TRouteHandler, localLanguage: string);
105
+ /**
106
+ * Method for creating a multi-router configuration
107
+ *
108
+ * @param controller
109
+ */
110
+ createMultipleRouterConfig(controller: any): IMultipleRouterConfig<TGatewayContext>;
111
+ /**
112
+ * Method for creating a router collection
113
+ *
114
+ * @param controller
115
+ * @param routes
116
+ */
117
+ createCollectionRouter(controller: any, routes: IMultipleRouterConfig<TGatewayContext>[]): void;
118
+ /**
119
+ * Get the standalone router
120
+ *
121
+ * @param strategy
122
+ * @param options
123
+ */
124
+ getStandaloneRoute(strategy?: string, options?: any): express.Router;
125
+ /**
126
+ * Get the definition of multiple routes
127
+ */
128
+ getMultipleRouteDefinition(): IMultipleRouteDefinition;
129
+ /**
130
+ *
131
+ */
132
+ getConfig(): IRouteConfig;
133
+ /**
134
+ * Utility method for creating an Opticore-compatible route
135
+ *
136
+ * @param path
137
+ * @param handler
138
+ */
139
+ static createOpticoreRouteDefinition(path: string, handler: TRouteHandler): {
140
+ path: string;
141
+ handler: any;
142
+ };
143
+ }
144
+
145
+ declare abstract class BaseMiddleware {
146
+ abstract handle(): TMiddlewareFunction;
147
+ }
148
+ declare class MiddlewareChain {
149
+ private middlewares;
150
+ add(middleware: TMiddlewareFunction): void;
151
+ execute(req: any, res: any, finalHandler: TMiddlewareFunction): Promise<void>;
152
+ getAll(): TMiddlewareFunction[];
153
+ }
154
+
155
+ /**
156
+ *
157
+ */
158
+ declare class ServiceRegistry {
159
+ private services;
160
+ private serviceHealthChecks;
161
+ private circuitBreakers;
162
+ registerService(service: IServiceConfig): void;
163
+ private startHealthCheck;
164
+ getServiceInstances(serviceName: string): IServiceInstance[];
165
+ getHealthyInstances(serviceName: string): IServiceInstance[];
166
+ recordSuccess(serviceName: string, url: string): void;
167
+ recordFailure(serviceName: string, url: string): void;
168
+ deregisterService(serviceName: string, url: string): void;
169
+ getAllServices(): Map<string, IServiceInstance[]>;
170
+ }
171
+
172
+ type TLoadBalancingStrategy = 'round-robin' | 'weighted' | 'random' | 'least-connections';
173
+
174
+ /**
175
+ *
176
+ */
177
+ declare class LoadBalancer {
178
+ private strategy;
179
+ private counters;
180
+ constructor(strategy?: TLoadBalancingStrategy);
181
+ /**
182
+ *
183
+ * @param serviceName
184
+ * @param instances
185
+ */
186
+ selectInstance(serviceName: string, instances: IServiceInstance[]): IServiceInstance | null;
187
+ /**
188
+ *
189
+ * @param serviceName
190
+ * @param instances
191
+ * @private
192
+ */
193
+ private roundRobin;
194
+ /**
195
+ *
196
+ * @param instances
197
+ * @private
198
+ */
199
+ private random;
200
+ /**
201
+ *
202
+ * @param instances
203
+ * @private
204
+ */
205
+ private weighted;
206
+ /**
207
+ *
208
+ * @param instances
209
+ * @private
210
+ */
211
+ private leastConnections;
212
+ /**
213
+ *
214
+ * @param strategy
215
+ */
216
+ setStrategy(strategy: TLoadBalancingStrategy): void;
217
+ }
218
+
219
+ interface IHttpResponse {
220
+ status: number;
221
+ headers: Record<string, string | string[]>;
222
+ body: string;
223
+ }
224
+
225
+ interface IHttpRequestOptions {
226
+ method: string;
227
+ headers?: http.OutgoingHttpHeaders | http.OutgoingHttpHeader[];
228
+ body?: any;
229
+ timeout?: number;
230
+ }
231
+
232
+ declare class HttpClient {
233
+ /**
234
+ *
235
+ * @param url
236
+ * @param options
237
+ */
238
+ request(url: string, options: IHttpRequestOptions): Promise<IHttpResponse>;
239
+ /**
240
+ *
241
+ * @param method
242
+ * @private
243
+ */
244
+ private getDefaultHeaders;
245
+ /**
246
+ *
247
+ * @param req
248
+ * @param body
249
+ * @param headers
250
+ * @private
251
+ */
252
+ private writeRequestBody;
253
+ /**
254
+ *
255
+ * @param headers
256
+ * @private
257
+ */
258
+ private getContentType;
259
+ /**
260
+ *
261
+ * @param url
262
+ * @param headers
263
+ */
264
+ get(url: string, headers?: Record<string, string>): Promise<IHttpResponse>;
265
+ /**
266
+ *
267
+ * @param url
268
+ * @param body
269
+ * @param headers
270
+ */
271
+ post(url: string, body: any, headers?: Record<string, string>): Promise<IHttpResponse>;
272
+ /**
273
+ *
274
+ * @param url
275
+ * @param body
276
+ * @param headers
277
+ */
278
+ put(url: string, body: any, headers?: Record<string, string>): Promise<IHttpResponse>;
279
+ /**
280
+ *
281
+ * @param url
282
+ * @param headers
283
+ */
284
+ delete(url: string, headers?: Record<string, string>): Promise<IHttpResponse>;
285
+ /**
286
+ *
287
+ * @param url
288
+ * @param body
289
+ * @param headers
290
+ */
291
+ patch(url: string, body: any, headers?: Record<string, string>): Promise<IHttpResponse>;
292
+ }
293
+
294
+ declare class AuthMiddleware extends BaseMiddleware {
295
+ private apiKeys;
296
+ constructor(apiKeys?: string[]);
297
+ handle(): TMiddlewareFunction;
298
+ }
299
+
300
+ /**
301
+ *
302
+ */
303
+ declare class RateLimitMiddleware extends BaseMiddleware {
304
+ private requestsPerWindow;
305
+ private windowMs;
306
+ private store;
307
+ constructor(requestsPerWindow?: number, windowMs?: number);
308
+ handle(): TMiddlewareFunction;
309
+ }
310
+
311
+ declare class LoggingMiddleware extends BaseMiddleware {
312
+ private logLevel;
313
+ constructor(logLevel?: 'info' | 'debug' | 'error');
314
+ handle(): TMiddlewareFunction;
315
+ }
316
+
317
+ declare class ValidationMiddleware extends BaseMiddleware {
318
+ private validator;
319
+ private target;
320
+ /**
321
+ * Crée un middleware de validation.
322
+ * @param schema - Le schéma de validation au format opticore-validator.
323
+ * @param target - La partie de la requête à valider (par défaut 'body').
324
+ */
325
+ constructor(schema: any, target?: 'body' | 'query' | 'params' | 'all');
326
+ handle(): TMiddlewareFunction;
327
+ }
328
+
329
+ export { APIGateway, AuthMiddleware, BaseMiddleware, GatewayRoute, HttpClient, type ICircuitBreakerConfig, type IGatewayConfig, type IRouteConfig, type IServiceConfig, LoadBalancer, LoggingMiddleware, MiddlewareChain, RateLimitMiddleware, ServiceRegistry, type TLoadBalancingStrategy, type TMiddlewareFunction, ValidationMiddleware };