@webpieces/http-filters 0.2.9 → 0.2.11

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/http-filters",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
4
4
  "description": "Filter chain infrastructure for cross-cutting concerns",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -21,6 +21,6 @@
21
21
  "access": "public"
22
22
  },
23
23
  "dependencies": {
24
- "@webpieces/core-context": "0.2.9"
24
+ "@webpieces/core-context": "0.2.11"
25
25
  }
26
26
  }
package/src/Filter.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Metadata about the method being invoked.
3
3
  * Passed to filters and contains request information.
4
4
  */
5
- export interface MethodMeta {
5
+ export declare class MethodMeta {
6
6
  /**
7
7
  * The HTTP method (GET, POST, etc.)
8
8
  */
@@ -32,16 +32,18 @@ export interface MethodMeta {
32
32
  * Additional metadata
33
33
  */
34
34
  metadata?: Map<string, any>;
35
+ constructor(httpMethod: string, path: string, methodName: string, params: any[], request?: any, response?: any, metadata?: Map<string, any>);
35
36
  }
36
37
  /**
37
38
  * Action returned by filters and controllers.
38
39
  * Can represent different types of responses.
39
40
  */
40
- export interface Action {
41
+ export declare class Action {
41
42
  type: 'json' | 'html' | 'redirect' | 'error';
42
43
  data?: any;
43
44
  statusCode?: number;
44
45
  headers?: Record<string, string>;
46
+ constructor(type: 'json' | 'html' | 'redirect' | 'error', data?: any, statusCode?: number, headers?: Record<string, string>);
45
47
  }
46
48
  /**
47
49
  * Next filter class.
package/src/Filter.js CHANGED
@@ -1,8 +1,37 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NextFilter = void 0;
3
+ exports.NextFilter = exports.Action = exports.MethodMeta = void 0;
4
4
  exports.jsonAction = jsonAction;
5
5
  exports.errorAction = errorAction;
6
+ /**
7
+ * Metadata about the method being invoked.
8
+ * Passed to filters and contains request information.
9
+ */
10
+ class MethodMeta {
11
+ constructor(httpMethod, path, methodName, params, request, response, metadata) {
12
+ this.httpMethod = httpMethod;
13
+ this.path = path;
14
+ this.methodName = methodName;
15
+ this.params = params;
16
+ this.request = request;
17
+ this.response = response;
18
+ this.metadata = metadata;
19
+ }
20
+ }
21
+ exports.MethodMeta = MethodMeta;
22
+ /**
23
+ * Action returned by filters and controllers.
24
+ * Can represent different types of responses.
25
+ */
26
+ class Action {
27
+ constructor(type, data, statusCode, headers) {
28
+ this.type = type;
29
+ this.data = data;
30
+ this.statusCode = statusCode;
31
+ this.headers = headers;
32
+ }
33
+ }
34
+ exports.Action = Action;
6
35
  /**
7
36
  * Next filter class.
8
37
  * This is a class instead of a function type to make it easier to trace
@@ -15,22 +44,14 @@ exports.NextFilter = NextFilter;
15
44
  * Helper to create a JSON action response.
16
45
  */
17
46
  function jsonAction(data, statusCode = 200) {
18
- return {
19
- type: 'json',
20
- data,
21
- statusCode,
22
- };
47
+ return new Action('json', data, statusCode);
23
48
  }
24
49
  /**
25
50
  * Helper to create an error action response.
26
51
  */
27
52
  function errorAction(error, statusCode = 500) {
28
- return {
29
- type: 'error',
30
- data: {
31
- error: typeof error === 'string' ? error : error.message,
32
- },
33
- statusCode,
34
- };
53
+ return new Action('error', {
54
+ error: typeof error === 'string' ? error : error.message,
55
+ }, statusCode);
35
56
  }
36
57
  //# sourceMappingURL=Filter.js.map
package/src/Filter.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Filter.js","sourceRoot":"","sources":["../../../../../packages/http/http-filters/src/Filter.ts"],"names":[],"mappings":";;;AAoHA,gCAMC;AAKD,kCAWC;AArFD;;;;GAIG;AACH,MAAsB,UAAU;CAM/B;AAND,gCAMC;AAiDD;;GAEG;AACH,SAAgB,UAAU,CAAC,IAAS,EAAE,aAAqB,GAAG;IAC5D,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,IAAI;QACJ,UAAU;KACX,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,SAAgB,WAAW,CACzB,KAAqB,EACrB,aAAqB,GAAG;IAExB,OAAO;QACL,IAAI,EAAE,OAAO;QACb,IAAI,EAAE;YACJ,KAAK,EAAE,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO;SACzD;QACD,UAAU;KACX,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Metadata about the method being invoked.\n * Passed to filters and contains request information.\n */\nexport interface MethodMeta {\n /**\n * The HTTP method (GET, POST, etc.)\n */\n httpMethod: string;\n\n /**\n * The request path\n */\n path: string;\n\n /**\n * The method name being invoked on the controller\n */\n methodName: string;\n\n /**\n * Parameters to pass to the controller method.\n * Filters can modify this array (e.g., JsonFilter deserializes request body into params[0])\n */\n params: any[];\n\n /**\n * The original request object (if applicable)\n */\n request?: any;\n\n /**\n * The response object (if applicable)\n */\n response?: any;\n\n /**\n * Additional metadata\n */\n metadata?: Map<string, any>;\n}\n\n/**\n * Action returned by filters and controllers.\n * Can represent different types of responses.\n */\nexport interface Action {\n type: 'json' | 'html' | 'redirect' | 'error';\n data?: any;\n statusCode?: number;\n headers?: Record<string, string>;\n}\n\n/**\n * Next filter class.\n * This is a class instead of a function type to make it easier to trace\n * who is calling what in the debugger/IDE.\n */\nexport abstract class NextFilter {\n /**\n * Execute the next filter in the chain.\n * @returns Promise of the action\n */\n abstract execute(): Promise<Action>;\n}\n\n/**\n * Filter interface.\n * Similar to Java WebPieces RouteFilter.\n *\n * Filters are executed in priority order (higher priority first)\n * and can wrap the execution of subsequent filters and the controller.\n *\n * Example:\n * ```typescript\n * @injectable()\n * export class LoggingFilter implements Filter {\n * priority = 100;\n *\n * async filter(meta: MethodMeta, next: NextFilter): Promise<Action> {\n * console.log(`Request: ${meta.httpMethod} ${meta.path}`);\n * const action = await next.execute();\n * console.log(`Response: ${action.statusCode}`);\n * return action;\n * }\n * }\n * ```\n */\nexport interface Filter {\n /**\n * Priority of this filter.\n * Higher numbers execute first.\n * Typical values:\n * - 140: Context setup\n * - 120: Request attributes\n * - 90: Metrics\n * - 80: Logging\n * - 60: JSON serialization\n * - 40: Transactions\n * - 0: Controller\n */\n priority: number;\n\n /**\n * Filter method that wraps the next filter/controller.\n *\n * @param meta - Metadata about the method being invoked\n * @param next - NextFilter instance to invoke the next filter in the chain\n * @returns Promise of the action to return\n */\n filter(meta: MethodMeta, next: NextFilter): Promise<Action>;\n}\n\n/**\n * Helper to create a JSON action response.\n */\nexport function jsonAction(data: any, statusCode: number = 200): Action {\n return {\n type: 'json',\n data,\n statusCode,\n };\n}\n\n/**\n * Helper to create an error action response.\n */\nexport function errorAction(\n error: Error | string,\n statusCode: number = 500\n): Action {\n return {\n type: 'error',\n data: {\n error: typeof error === 'string' ? error : error.message,\n },\n statusCode,\n };\n}\n"]}
1
+ {"version":3,"file":"Filter.js","sourceRoot":"","sources":["../../../../../packages/http/http-filters/src/Filter.ts"],"names":[],"mappings":";;;AAkJA,gCAEC;AAKD,kCAWC;AApKD;;;GAGG;AACH,MAAa,UAAU;IAqCrB,YACE,UAAkB,EAClB,IAAY,EACZ,UAAkB,EAClB,MAAa,EACb,OAAa,EACb,QAAc,EACd,QAA2B;QAE3B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF;AAtDD,gCAsDC;AAED;;;GAGG;AACH,MAAa,MAAM;IAMjB,YACE,IAA4C,EAC5C,IAAU,EACV,UAAmB,EACnB,OAAgC;QAEhC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAjBD,wBAiBC;AAED;;;;GAIG;AACH,MAAsB,UAAU;CAM/B;AAND,gCAMC;AAiDD;;GAEG;AACH,SAAgB,UAAU,CAAC,IAAS,EAAE,aAAqB,GAAG;IAC5D,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC;AAC9C,CAAC;AAED;;GAEG;AACH,SAAgB,WAAW,CACzB,KAAqB,EACrB,aAAqB,GAAG;IAExB,OAAO,IAAI,MAAM,CACf,OAAO,EACP;QACE,KAAK,EAAE,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO;KACzD,EACD,UAAU,CACX,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Metadata about the method being invoked.\n * Passed to filters and contains request information.\n */\nexport class MethodMeta {\n /**\n * The HTTP method (GET, POST, etc.)\n */\n httpMethod: string;\n\n /**\n * The request path\n */\n path: string;\n\n /**\n * The method name being invoked on the controller\n */\n methodName: string;\n\n /**\n * Parameters to pass to the controller method.\n * Filters can modify this array (e.g., JsonFilter deserializes request body into params[0])\n */\n params: any[];\n\n /**\n * The original request object (if applicable)\n */\n request?: any;\n\n /**\n * The response object (if applicable)\n */\n response?: any;\n\n /**\n * Additional metadata\n */\n metadata?: Map<string, any>;\n\n constructor(\n httpMethod: string,\n path: string,\n methodName: string,\n params: any[],\n request?: any,\n response?: any,\n metadata?: Map<string, any>\n ) {\n this.httpMethod = httpMethod;\n this.path = path;\n this.methodName = methodName;\n this.params = params;\n this.request = request;\n this.response = response;\n this.metadata = metadata;\n }\n}\n\n/**\n * Action returned by filters and controllers.\n * Can represent different types of responses.\n */\nexport class Action {\n type: 'json' | 'html' | 'redirect' | 'error';\n data?: any;\n statusCode?: number;\n headers?: Record<string, string>;\n\n constructor(\n type: 'json' | 'html' | 'redirect' | 'error',\n data?: any,\n statusCode?: number,\n headers?: Record<string, string>\n ) {\n this.type = type;\n this.data = data;\n this.statusCode = statusCode;\n this.headers = headers;\n }\n}\n\n/**\n * Next filter class.\n * This is a class instead of a function type to make it easier to trace\n * who is calling what in the debugger/IDE.\n */\nexport abstract class NextFilter {\n /**\n * Execute the next filter in the chain.\n * @returns Promise of the action\n */\n abstract execute(): Promise<Action>;\n}\n\n/**\n * Filter interface.\n * Similar to Java WebPieces RouteFilter.\n *\n * Filters are executed in priority order (higher priority first)\n * and can wrap the execution of subsequent filters and the controller.\n *\n * Example:\n * ```typescript\n * @injectable()\n * export class LoggingFilter implements Filter {\n * priority = 100;\n *\n * async filter(meta: MethodMeta, next: NextFilter): Promise<Action> {\n * console.log(`Request: ${meta.httpMethod} ${meta.path}`);\n * const action = await next.execute();\n * console.log(`Response: ${action.statusCode}`);\n * return action;\n * }\n * }\n * ```\n */\nexport interface Filter {\n /**\n * Priority of this filter.\n * Higher numbers execute first.\n * Typical values:\n * - 140: Context setup\n * - 120: Request attributes\n * - 90: Metrics\n * - 80: Logging\n * - 60: JSON serialization\n * - 40: Transactions\n * - 0: Controller\n */\n priority: number;\n\n /**\n * Filter method that wraps the next filter/controller.\n *\n * @param meta - Metadata about the method being invoked\n * @param next - NextFilter instance to invoke the next filter in the chain\n * @returns Promise of the action to return\n */\n filter(meta: MethodMeta, next: NextFilter): Promise<Action>;\n}\n\n/**\n * Helper to create a JSON action response.\n */\nexport function jsonAction(data: any, statusCode: number = 200): Action {\n return new Action('json', data, statusCode);\n}\n\n/**\n * Helper to create an error action response.\n */\nexport function errorAction(\n error: Error | string,\n statusCode: number = 500\n): Action {\n return new Action(\n 'error',\n {\n error: typeof error === 'string' ? error : error.message,\n },\n statusCode\n );\n}\n"]}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ContextFilter = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const inversify_1 = require("inversify");
6
+ const http_routing_1 = require("@webpieces/http-routing");
6
7
  const core_context_1 = require("@webpieces/core-context");
7
8
  /**
8
9
  * ContextFilter - Sets up AsyncLocalStorage context for each request.
@@ -17,24 +18,19 @@ let ContextFilter = class ContextFilter {
17
18
  }
18
19
  async filter(meta, next) {
19
20
  // Run the rest of the filter chain within a new context
20
- return core_context_1.Context.run(async () => {
21
+ return core_context_1.RequestContext.run(async () => {
21
22
  // Store request metadata in context for other filters to access
22
- core_context_1.Context.put('METHOD_META', meta);
23
- core_context_1.Context.put('REQUEST_PATH', meta.path);
24
- core_context_1.Context.put('HTTP_METHOD', meta.httpMethod);
25
- try {
26
- return await next.execute();
27
- }
28
- finally {
29
- // Clean up context (AsyncLocalStorage handles this automatically,
30
- // but we can explicitly clear if needed)
31
- core_context_1.Context.clear();
32
- }
23
+ core_context_1.RequestContext.put('METHOD_META', meta);
24
+ core_context_1.RequestContext.put('REQUEST_PATH', meta.path);
25
+ core_context_1.RequestContext.put('HTTP_METHOD', meta.httpMethod);
26
+ return await next.execute();
27
+ //RequestContext is auto cleared when done.
33
28
  });
34
29
  }
35
30
  };
36
31
  exports.ContextFilter = ContextFilter;
37
32
  exports.ContextFilter = ContextFilter = tslib_1.__decorate([
33
+ (0, http_routing_1.provideSingleton)(),
38
34
  (0, inversify_1.injectable)()
39
35
  ], ContextFilter);
40
36
  //# sourceMappingURL=ContextFilter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ContextFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-filters/src/filters/ContextFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAAuC;AACvC,0DAAkD;AAGlD;;;;;;GAMG;AAEI,IAAM,aAAa,GAAnB,MAAM,aAAa;IAAnB;QACL,aAAQ,GAAG,GAAG,CAAC;IAmBjB,CAAC;IAjBC,KAAK,CAAC,MAAM,CAAC,IAAgB,EAAE,IAAgB;QAC7C,wDAAwD;QACxD,OAAO,sBAAO,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YAC5B,gEAAgE;YAChE,sBAAO,CAAC,GAAG,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;YACjC,sBAAO,CAAC,GAAG,CAAC,cAAc,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;YACvC,sBAAO,CAAC,GAAG,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAE5C,IAAI,CAAC;gBACH,OAAO,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;YAC9B,CAAC;oBAAS,CAAC;gBACT,kEAAkE;gBAClE,yCAAyC;gBACzC,sBAAO,CAAC,KAAK,EAAE,CAAC;YAClB,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AApBY,sCAAa;wBAAb,aAAa;IADzB,IAAA,sBAAU,GAAE;GACA,aAAa,CAoBzB","sourcesContent":["import { injectable } from 'inversify';\nimport { Context } from '@webpieces/core-context';\nimport { Filter, MethodMeta, Action, NextFilter } from '../Filter';\n\n/**\n * ContextFilter - Sets up AsyncLocalStorage context for each request.\n * Priority: 140 (executes first)\n *\n * This filter ensures that all subsequent filters and the controller\n * execute within a context that can store request-scoped data.\n */\n@injectable()\nexport class ContextFilter implements Filter {\n priority = 140;\n\n async filter(meta: MethodMeta, next: NextFilter): Promise<Action> {\n // Run the rest of the filter chain within a new context\n return Context.run(async () => {\n // Store request metadata in context for other filters to access\n Context.put('METHOD_META', meta);\n Context.put('REQUEST_PATH', meta.path);\n Context.put('HTTP_METHOD', meta.httpMethod);\n\n try {\n return await next.execute();\n } finally {\n // Clean up context (AsyncLocalStorage handles this automatically,\n // but we can explicitly clear if needed)\n Context.clear();\n }\n });\n }\n}\n"]}
1
+ {"version":3,"file":"ContextFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-filters/src/filters/ContextFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAAuC;AACvC,0DAA2D;AAC3D,0DAAyD;AAGzD;;;;;;GAMG;AAGI,IAAM,aAAa,GAAnB,MAAM,aAAa;IAAnB;QACL,aAAQ,GAAG,GAAG,CAAC;IAcjB,CAAC;IAZC,KAAK,CAAC,MAAM,CAAC,IAAgB,EAAE,IAAgB;QAC7C,wDAAwD;QACxD,OAAO,6BAAc,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YACnC,gEAAgE;YAChE,6BAAc,CAAC,GAAG,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;YACxC,6BAAc,CAAC,GAAG,CAAC,cAAc,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;YAC9C,6BAAc,CAAC,GAAG,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAEjD,OAAO,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;YAC5B,2CAA2C;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAfY,sCAAa;wBAAb,aAAa;IAFzB,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;GACA,aAAa,CAezB","sourcesContent":["import { injectable } from 'inversify';\nimport { provideSingleton } from '@webpieces/http-routing';\nimport { RequestContext } from '@webpieces/core-context';\nimport { Filter, MethodMeta, Action, NextFilter } from '../Filter';\n\n/**\n * ContextFilter - Sets up AsyncLocalStorage context for each request.\n * Priority: 140 (executes first)\n *\n * This filter ensures that all subsequent filters and the controller\n * execute within a context that can store request-scoped data.\n */\n@provideSingleton()\n@injectable()\nexport class ContextFilter implements Filter {\n priority = 140;\n\n async filter(meta: MethodMeta, next: NextFilter): Promise<Action> {\n // Run the rest of the filter chain within a new context\n return RequestContext.run(async () => {\n // Store request metadata in context for other filters to access\n RequestContext.put('METHOD_META', meta);\n RequestContext.put('REQUEST_PATH', meta.path);\n RequestContext.put('HTTP_METHOD', meta.httpMethod);\n\n return await next.execute();\n //RequestContext is auto cleared when done.\n });\n }\n}\n"]}
@@ -1,18 +1,35 @@
1
1
  import { Filter, MethodMeta, Action, NextFilter } from '../Filter';
2
+ /**
3
+ * DI tokens for http-filters.
4
+ */
5
+ export declare const FILTER_TYPES: {
6
+ JsonFilterConfig: symbol;
7
+ };
2
8
  /**
3
9
  * Configuration for JsonFilter.
10
+ * Register this in your DI container to customize JsonFilter behavior.
11
+ *
12
+ * Example:
13
+ * ```typescript
14
+ * export const MyModule = new ContainerModule((bind) => {
15
+ * bind(FILTER_TYPES.JsonFilterConfig).toConstantValue(
16
+ * new JsonFilterConfig(true, true) // validation enabled, logging enabled
17
+ * );
18
+ * });
19
+ * ```
4
20
  */
5
- export interface JsonFilterConfig {
21
+ export declare class JsonFilterConfig {
6
22
  /**
7
23
  * Whether to enable validation using class-validator.
8
24
  * Default: true
9
25
  */
10
- validationEnabled?: boolean;
26
+ validationEnabled: boolean;
11
27
  /**
12
28
  * Whether to log requests and responses.
13
29
  * Default: false
14
30
  */
15
- loggingEnabled?: boolean;
31
+ loggingEnabled: boolean;
32
+ constructor(validationEnabled?: boolean, loggingEnabled?: boolean);
16
33
  }
17
34
  /**
18
35
  * JsonFilter - Handles JSON deserialization and serialization.
@@ -26,11 +43,16 @@ export interface JsonFilterConfig {
26
43
  * 3. Execute next filter/controller
27
44
  * 4. Serialize response to JSON
28
45
  * 5. Handle errors and translate to JSON error responses
46
+ *
47
+ * Configuration:
48
+ * JsonFilter uses constructor injection to receive JsonFilterConfig.
49
+ * The default config has validation enabled and logging disabled.
50
+ * To customize, bind JsonFilterConfig in your DI module.
29
51
  */
30
52
  export declare class JsonFilter implements Filter {
31
53
  private config;
32
54
  priority: number;
33
- constructor(config?: JsonFilterConfig);
55
+ constructor(config: JsonFilterConfig);
34
56
  filter(meta: MethodMeta, next: NextFilter): Promise<Action>;
35
57
  /**
36
58
  * Process the request: deserialize and validate.
@@ -1,10 +1,41 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpException = exports.ValidationException = exports.JsonFilter = void 0;
3
+ exports.HttpException = exports.ValidationException = exports.JsonFilter = exports.JsonFilterConfig = exports.FILTER_TYPES = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const inversify_1 = require("inversify");
6
+ const http_routing_1 = require("@webpieces/http-routing");
6
7
  const class_validator_1 = require("class-validator");
7
8
  const Filter_1 = require("../Filter");
9
+ /**
10
+ * DI tokens for http-filters.
11
+ */
12
+ exports.FILTER_TYPES = {
13
+ JsonFilterConfig: Symbol.for('JsonFilterConfig'),
14
+ };
15
+ /**
16
+ * Configuration for JsonFilter.
17
+ * Register this in your DI container to customize JsonFilter behavior.
18
+ *
19
+ * Example:
20
+ * ```typescript
21
+ * export const MyModule = new ContainerModule((bind) => {
22
+ * bind(FILTER_TYPES.JsonFilterConfig).toConstantValue(
23
+ * new JsonFilterConfig(true, true) // validation enabled, logging enabled
24
+ * );
25
+ * });
26
+ * ```
27
+ */
28
+ let JsonFilterConfig = class JsonFilterConfig {
29
+ constructor(validationEnabled = true, loggingEnabled = false) {
30
+ this.validationEnabled = validationEnabled;
31
+ this.loggingEnabled = loggingEnabled;
32
+ }
33
+ };
34
+ exports.JsonFilterConfig = JsonFilterConfig;
35
+ exports.JsonFilterConfig = JsonFilterConfig = tslib_1.__decorate([
36
+ (0, inversify_1.injectable)(),
37
+ tslib_1.__metadata("design:paramtypes", [Boolean, Boolean])
38
+ ], JsonFilterConfig);
8
39
  /**
9
40
  * JsonFilter - Handles JSON deserialization and serialization.
10
41
  * Priority: 60
@@ -17,16 +48,17 @@ const Filter_1 = require("../Filter");
17
48
  * 3. Execute next filter/controller
18
49
  * 4. Serialize response to JSON
19
50
  * 5. Handle errors and translate to JSON error responses
51
+ *
52
+ * Configuration:
53
+ * JsonFilter uses constructor injection to receive JsonFilterConfig.
54
+ * The default config has validation enabled and logging disabled.
55
+ * To customize, bind JsonFilterConfig in your DI module.
20
56
  */
21
57
  let JsonFilter = class JsonFilter {
22
- constructor(config = {}) {
58
+ constructor(config) {
23
59
  this.config = config;
24
60
  this.priority = 60;
25
- this.config = {
26
- validationEnabled: true,
27
- loggingEnabled: false,
28
- ...config,
29
- };
61
+ // Config is injected from DI container
30
62
  }
31
63
  async filter(meta, next) {
32
64
  try {
@@ -138,9 +170,10 @@ let JsonFilter = class JsonFilter {
138
170
  };
139
171
  exports.JsonFilter = JsonFilter;
140
172
  exports.JsonFilter = JsonFilter = tslib_1.__decorate([
173
+ (0, http_routing_1.provideSingleton)(),
141
174
  (0, inversify_1.injectable)(),
142
- tslib_1.__param(0, (0, inversify_1.unmanaged)()),
143
- tslib_1.__metadata("design:paramtypes", [Object])
175
+ tslib_1.__param(0, (0, inversify_1.inject)(exports.FILTER_TYPES.JsonFilterConfig)),
176
+ tslib_1.__metadata("design:paramtypes", [JsonFilterConfig])
144
177
  ], JsonFilter);
145
178
  /**
146
179
  * Exception thrown when validation fails.
@@ -1 +1 @@
1
- {"version":3,"file":"JsonFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-filters/src/filters/JsonFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAAkD;AAElD,qDAA4D;AAC5D,sCAA4F;AAoB5F;;;;;;;;;;;;GAYG;AAEI,IAAM,UAAU,GAAhB,MAAM,UAAU;IAGrB,YAAyB,SAAmC,EAAE;QAA7B,WAAM,GAAN,MAAM,CAAuB;QAF9D,aAAQ,GAAG,EAAE,CAAC;QAGZ,IAAI,CAAC,MAAM,GAAG;YACZ,iBAAiB,EAAE,IAAI;YACvB,cAAc,EAAE,KAAK;YACrB,GAAG,MAAM;SACV,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,IAAgB,EAAE,IAAgB;QAC7C,IAAI,CAAC;YACH,qDAAqD;YACrD,MAAM,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;YAEhC,IAAI,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;gBAC/B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YACxB,CAAC;YAED,iC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AAC,OAAO,CAAC,CAAC;QADmB,eAAU,GAAV,UAAU,CAAQ;QAEpD,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AALD,sCAKC","sourcesContent":["import { injectable, unmanaged } from 'inversify';\nimport { plainToInstance } from 'class-transformer';\nimport { validate, ValidationError } from 'class-validator';\nimport { Filter, MethodMeta, Action, NextFilter, jsonAction, errorAction } from '../Filter';\nimport { Context } from '@webpieces/core-context';\n\n/**\n * Configuration for JsonFilter.\n */\nexport interface JsonFilterConfig {\n /**\n * Whether to enable validation using class-validator.\n * Default: true\n */\n validationEnabled?: boolean;\n\n /**\n * Whether to log requests and responses.\n * Default: false\n */\n loggingEnabled?: boolean;\n}\n\n/**\n * JsonFilter - Handles JSON deserialization and serialization.\n * Priority: 60\n *\n * Similar to Java WebPieces JacksonCatchAllFilter.\n *\n * Responsibilities:\n * 1. Deserialize request body to DTO (if request has body)\n * 2. Validate DTO using class-validator (if enabled)\n * 3. Execute next filter/controller\n * 4. Serialize response to JSON\n * 5. Handle errors and translate to JSON error responses\n */\n@injectable()\nexport class JsonFilter implements Filter {\n priority = 60;\n\n constructor(@unmanaged() private config: JsonFilterConfig = {}) {\n this.config = {\n validationEnabled: true,\n loggingEnabled: false,\n ...config,\n };\n }\n\n async filter(meta: MethodMeta, next: NextFilter): Promise<Action> {\n try {\n // Deserialize and validate request if there's a body\n await this.processRequest(meta);\n\n if (this.config.loggingEnabled) {\n this.logRequest(meta);\n }\n\n // Execute next filter/controller\n const action = await next.execute();\n\n if (this.config.loggingEnabled) {\n this.logResponse(action);\n }\n\n // Ensure response is JSON\n if (action.type !== 'json' && action.type !== 'error') {\n return jsonAction(action.data);\n }\n\n return action;\n } catch (error) {\n // Translate error to JSON response\n return this.handleError(error, meta);\n }\n }\n\n /**\n * Process the request: deserialize and validate.\n */\n private async processRequest(meta: MethodMeta): Promise<void> {\n // If there's request data and a parameter type, deserialize it\n if (meta.request?.body && meta.params.length === 0) {\n const body = meta.request.body;\n\n // For now, we'll just pass the body as-is\n // In a real implementation, we'd use the parameter type from decorators\n // to properly deserialize and validate\n\n // If we have type information, we can do proper transformation\n // For this MVP, we'll store the body in params[0]\n meta.params[0] = body;\n\n // If validation is enabled and we have a class instance, validate it\n if (this.config.validationEnabled && body.constructor !== Object) {\n await this.validateDto(body);\n }\n }\n }\n\n /**\n * Validate a DTO using class-validator.\n */\n private async validateDto(dto: any): Promise<void> {\n const errors = await validate(dto);\n\n if (errors.length > 0) {\n const messages = this.formatValidationErrors(errors);\n throw new ValidationException(messages);\n }\n }\n\n /**\n * Format validation errors into a readable format.\n */\n private formatValidationErrors(errors: ValidationError[]): string[] {\n const messages: string[] = [];\n\n for (const error of errors) {\n if (error.constraints) {\n const constraints = Object.values(error.constraints);\n messages.push(...constraints);\n }\n\n if (error.children && error.children.length > 0) {\n const childMessages = this.formatValidationErrors(error.children);\n messages.push(...childMessages);\n }\n }\n\n return messages;\n }\n\n /**\n * Handle errors and translate to JSON error responses.\n */\n private handleError(error: any, meta: MethodMeta): Action {\n if (error instanceof ValidationException) {\n return errorAction(\n {\n error: 'Validation failed',\n violations: error.violations,\n } as any,\n 400\n );\n }\n\n if (error instanceof HttpException) {\n return errorAction(\n {\n error: error.message,\n code: error.statusCode,\n } as any,\n error.statusCode\n );\n }\n\n // Log unexpected errors\n console.error('Unexpected error in filter chain:', error);\n\n return errorAction(\n 'Internal server error',\n 500\n );\n }\n\n /**\n * Log the incoming request.\n */\n private logRequest(meta: MethodMeta): void {\n console.log(`[JsonFilter] ${meta.httpMethod} ${meta.path}`);\n if (meta.params.length > 0) {\n console.log('[JsonFilter] Request body:', JSON.stringify(meta.params[0], null, 2));\n }\n }\n\n /**\n * Log the outgoing response.\n */\n private logResponse(action: Action): void {\n console.log(`[JsonFilter] Response: ${action.statusCode}`);\n if (action.data) {\n console.log('[JsonFilter] Response body:', JSON.stringify(action.data, null, 2));\n }\n }\n}\n\n/**\n * Exception thrown when validation fails.\n */\nexport class ValidationException extends Error {\n constructor(public violations: string[]) {\n super('Validation failed');\n this.name = 'ValidationException';\n }\n}\n\n/**\n * HTTP exception with status code.\n */\nexport class HttpException extends Error {\n constructor(message: string, public statusCode: number) {\n super(message);\n this.name = 'HttpException';\n }\n}\n"]}
1
+ {"version":3,"file":"JsonFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-filters/src/filters/JsonFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAA+C;AAC/C,0DAA2D;AAE3D,qDAA4D;AAC5D,sCAA4F;AAG5F;;GAEG;AACU,QAAA,YAAY,GAAG;IAC1B,gBAAgB,EAAE,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC;CACjD,CAAC;AAEF;;;;;;;;;;;;GAYG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAa3B,YACE,oBAA6B,IAAI,EACjC,iBAA0B,KAAK;QAE/B,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;CACF,CAAA;AApBY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,GAAE;;GACA,gBAAgB,CAoB5B;AAED;;;;;;;;;;;;;;;;;GAiBG;AAGI,IAAM,UAAU,GAAhB,MAAM,UAAU;IAGrB,YAAmD,MAAgC;QAAxB,WAAM,GAAN,MAAM,CAAkB;QAFnF,aAAQ,GAAG,EAAE,CAAC;QAGZ,uCAAuC;IACzC,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,IAAgB,EAAE,IAAgB;QAC7C,IAAI,CAAC;YACH,qDAAqD;YACrD,MAAM,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;YAEhC,IAAI,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;gBAC/B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YACxB,CAAC;YAED,iCAAiC;YACjC,MAAM,MAAM,GAAG,MAAM,IAAI,CAA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EAAS,UAAkB;QACpD,KAAK,CAAC,OAAO,CAAC,CAAC;QADmB,eAAU,GAAV,UAAU,CAAQ;QAEpD,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AALD,sCAKC","sourcesContent":["import { injectable, inject } from 'inversify';\nimport { provideSingleton } from '@webpieces/http-routing';\nimport { plainToInstance } from 'class-transformer';\nimport { validate, ValidationError } from 'class-validator';\nimport { Filter, MethodMeta, Action, NextFilter, jsonAction, errorAction } from '../Filter';\nimport { RequestContext } from '@webpieces/core-context';\n\n/**\n * DI tokens for http-filters.\n */\nexport const FILTER_TYPES = {\n JsonFilterConfig: Symbol.for('JsonFilterConfig'),\n};\n\n/**\n * Configuration for JsonFilter.\n * Register this in your DI container to customize JsonFilter behavior.\n *\n * Example:\n * ```typescript\n * export const MyModule = new ContainerModule((bind) => {\n * bind(FILTER_TYPES.JsonFilterConfig).toConstantValue(\n * new JsonFilterConfig(true, true) // validation enabled, logging enabled\n * );\n * });\n * ```\n */\n@injectable()\nexport class JsonFilterConfig {\n /**\n * Whether to enable validation using class-validator.\n * Default: true\n */\n validationEnabled: boolean;\n\n /**\n * Whether to log requests and responses.\n * Default: false\n */\n loggingEnabled: boolean;\n\n constructor(\n validationEnabled: boolean = true,\n loggingEnabled: boolean = false\n ) {\n this.validationEnabled = validationEnabled;\n this.loggingEnabled = loggingEnabled;\n }\n}\n\n/**\n * JsonFilter - Handles JSON deserialization and serialization.\n * Priority: 60\n *\n * Similar to Java WebPieces JacksonCatchAllFilter.\n *\n * Responsibilities:\n * 1. Deserialize request body to DTO (if request has body)\n * 2. Validate DTO using class-validator (if enabled)\n * 3. Execute next filter/controller\n * 4. Serialize response to JSON\n * 5. Handle errors and translate to JSON error responses\n *\n * Configuration:\n * JsonFilter uses constructor injection to receive JsonFilterConfig.\n * The default config has validation enabled and logging disabled.\n * To customize, bind JsonFilterConfig in your DI module.\n */\n@provideSingleton()\n@injectable()\nexport class JsonFilter implements Filter {\n priority = 60;\n\n constructor(@inject(FILTER_TYPES.JsonFilterConfig) private config: JsonFilterConfig) {\n // Config is injected from DI container\n }\n\n async filter(meta: MethodMeta, next: NextFilter): Promise<Action> {\n try {\n // Deserialize and validate request if there's a body\n await this.processRequest(meta);\n\n if (this.config.loggingEnabled) {\n this.logRequest(meta);\n }\n\n // Execute next filter/controller\n const action = await next.execute();\n\n if (this.config.loggingEnabled) {\n this.logResponse(action);\n }\n\n // Ensure response is JSON\n if (action.type !== 'json' && action.type !== 'error') {\n return jsonAction(action.data);\n }\n\n return action;\n } catch (error) {\n // Translate error to JSON response\n return this.handleError(error, meta);\n }\n }\n\n /**\n * Process the request: deserialize and validate.\n */\n private async processRequest(meta: MethodMeta): Promise<void> {\n // If there's request data and a parameter type, deserialize it\n if (meta.request?.body && meta.params.length === 0) {\n const body = meta.request.body;\n\n // For now, we'll just pass the body as-is\n // In a real implementation, we'd use the parameter type from decorators\n // to properly deserialize and validate\n\n // If we have type information, we can do proper transformation\n // For this MVP, we'll store the body in params[0]\n meta.params[0] = body;\n\n // If validation is enabled and we have a class instance, validate it\n if (this.config.validationEnabled && body.constructor !== Object) {\n await this.validateDto(body);\n }\n }\n }\n\n /**\n * Validate a DTO using class-validator.\n */\n private async validateDto(dto: any): Promise<void> {\n const errors = await validate(dto);\n\n if (errors.length > 0) {\n const messages = this.formatValidationErrors(errors);\n throw new ValidationException(messages);\n }\n }\n\n /**\n * Format validation errors into a readable format.\n */\n private formatValidationErrors(errors: ValidationError[]): string[] {\n const messages: string[] = [];\n\n for (const error of errors) {\n if (error.constraints) {\n const constraints = Object.values(error.constraints);\n messages.push(...constraints);\n }\n\n if (error.children && error.children.length > 0) {\n const childMessages = this.formatValidationErrors(error.children);\n messages.push(...childMessages);\n }\n }\n\n return messages;\n }\n\n /**\n * Handle errors and translate to JSON error responses.\n */\n private handleError(error: any, meta: MethodMeta): Action {\n if (error instanceof ValidationException) {\n return errorAction(\n {\n error: 'Validation failed',\n violations: error.violations,\n } as any,\n 400\n );\n }\n\n if (error instanceof HttpException) {\n return errorAction(\n {\n error: error.message,\n code: error.statusCode,\n } as any,\n error.statusCode\n );\n }\n\n // Log unexpected errors\n console.error('Unexpected error in filter chain:', error);\n\n return errorAction(\n 'Internal server error',\n 500\n );\n }\n\n /**\n * Log the incoming request.\n */\n private logRequest(meta: MethodMeta): void {\n console.log(`[JsonFilter] ${meta.httpMethod} ${meta.path}`);\n if (meta.params.length > 0) {\n console.log('[JsonFilter] Request body:', JSON.stringify(meta.params[0], null, 2));\n }\n }\n\n /**\n * Log the outgoing response.\n */\n private logResponse(action: Action): void {\n console.log(`[JsonFilter] Response: ${action.statusCode}`);\n if (action.data) {\n console.log('[JsonFilter] Response body:', JSON.stringify(action.data, null, 2));\n }\n }\n}\n\n/**\n * Exception thrown when validation fails.\n */\nexport class ValidationException extends Error {\n constructor(public violations: string[]) {\n super('Validation failed');\n this.name = 'ValidationException';\n }\n}\n\n/**\n * HTTP exception with status code.\n */\nexport class HttpException extends Error {\n constructor(message: string, public statusCode: number) {\n super(message);\n this.name = 'HttpException';\n }\n}\n"]}
package/src/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { Filter, MethodMeta, Action, NextFilter, jsonAction, errorAction, } from './Filter';
2
2
  export { FilterChain } from './FilterChain';
3
3
  export { ContextFilter } from './filters/ContextFilter';
4
- export { JsonFilter, JsonFilterConfig, ValidationException, HttpException, } from './filters/JsonFilter';
4
+ export { JsonFilter, JsonFilterConfig, FILTER_TYPES, ValidationException, HttpException, } from './filters/JsonFilter';
package/src/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpException = exports.ValidationException = exports.JsonFilter = exports.ContextFilter = exports.FilterChain = exports.errorAction = exports.jsonAction = exports.NextFilter = void 0;
3
+ exports.HttpException = exports.ValidationException = exports.FILTER_TYPES = exports.JsonFilterConfig = exports.JsonFilter = exports.ContextFilter = exports.FilterChain = exports.errorAction = exports.jsonAction = exports.NextFilter = exports.Action = exports.MethodMeta = void 0;
4
4
  var Filter_1 = require("./Filter");
5
+ Object.defineProperty(exports, "MethodMeta", { enumerable: true, get: function () { return Filter_1.MethodMeta; } });
6
+ Object.defineProperty(exports, "Action", { enumerable: true, get: function () { return Filter_1.Action; } });
5
7
  Object.defineProperty(exports, "NextFilter", { enumerable: true, get: function () { return Filter_1.NextFilter; } });
6
8
  Object.defineProperty(exports, "jsonAction", { enumerable: true, get: function () { return Filter_1.jsonAction; } });
7
9
  Object.defineProperty(exports, "errorAction", { enumerable: true, get: function () { return Filter_1.errorAction; } });
@@ -11,6 +13,8 @@ var ContextFilter_1 = require("./filters/ContextFilter");
11
13
  Object.defineProperty(exports, "ContextFilter", { enumerable: true, get: function () { return ContextFilter_1.ContextFilter; } });
12
14
  var JsonFilter_1 = require("./filters/JsonFilter");
13
15
  Object.defineProperty(exports, "JsonFilter", { enumerable: true, get: function () { return JsonFilter_1.JsonFilter; } });
16
+ Object.defineProperty(exports, "JsonFilterConfig", { enumerable: true, get: function () { return JsonFilter_1.JsonFilterConfig; } });
17
+ Object.defineProperty(exports, "FILTER_TYPES", { enumerable: true, get: function () { return JsonFilter_1.FILTER_TYPES; } });
14
18
  Object.defineProperty(exports, "ValidationException", { enumerable: true, get: function () { return JsonFilter_1.ValidationException; } });
15
19
  Object.defineProperty(exports, "HttpException", { enumerable: true, get: function () { return JsonFilter_1.HttpException; } });
16
20
  //# sourceMappingURL=index.js.map
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-filters/src/index.ts"],"names":[],"mappings":";;;AAAA,mCAOkB;AAHhB,oGAAA,UAAU,OAAA;AACV,oGAAA,UAAU,OAAA;AACV,qGAAA,WAAW,OAAA;AAGb,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AAEpB,yDAAwD;AAA/C,8GAAA,aAAa,OAAA;AACtB,mDAK8B;AAJ5B,wGAAA,UAAU,OAAA;AAEV,iHAAA,mBAAmB,OAAA;AACnB,2GAAA,aAAa,OAAA","sourcesContent":["export {\n Filter,\n MethodMeta,\n Action,\n NextFilter,\n jsonAction,\n errorAction,\n} from './Filter';\n\nexport { FilterChain } from './FilterChain';\n\nexport { ContextFilter } from './filters/ContextFilter';\nexport {\n JsonFilter,\n JsonFilterConfig,\n ValidationException,\n HttpException,\n} from './filters/JsonFilter';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-filters/src/index.ts"],"names":[],"mappings":";;;AAAA,mCAOkB;AALhB,oGAAA,UAAU,OAAA;AACV,gGAAA,MAAM,OAAA;AACN,oGAAA,UAAU,OAAA;AACV,oGAAA,UAAU,OAAA;AACV,qGAAA,WAAW,OAAA;AAGb,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AAEpB,yDAAwD;AAA/C,8GAAA,aAAa,OAAA;AACtB,mDAM8B;AAL5B,wGAAA,UAAU,OAAA;AACV,8GAAA,gBAAgB,OAAA;AAChB,0GAAA,YAAY,OAAA;AACZ,iHAAA,mBAAmB,OAAA;AACnB,2GAAA,aAAa,OAAA","sourcesContent":["export {\n Filter,\n MethodMeta,\n Action,\n NextFilter,\n jsonAction,\n errorAction,\n} from './Filter';\n\nexport { FilterChain } from './FilterChain';\n\nexport { ContextFilter } from './filters/ContextFilter';\nexport {\n JsonFilter,\n JsonFilterConfig,\n FILTER_TYPES,\n ValidationException,\n HttpException,\n} from './filters/JsonFilter';\n"]}