@leancodepl/validation 8.4.0 → 8.5.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/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # @leancodepl/validation
2
+
3
+ TypeScript library for handling validation errors in CQRS command responses with type-safe error code mapping.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @leancodepl/validation
9
+ # or
10
+ yarn add @leancodepl/validation
11
+ ```
12
+
13
+ ## API
14
+
15
+ ### `handleValidationErrors(validationErrors, errorCodesMap, validationResults)`
16
+
17
+ Creates a validation error handler that processes errors with type-safe error code mapping.
18
+
19
+ **Parameters:**
20
+
21
+ - `validationErrors: ValidationError<TAllErrors>[]` - Array of validation errors to process
22
+ - `errorCodesMap: TAllErrors` - Mapping of error names to numeric codes
23
+ - `validationResults?: TInResult[]` - Optional array of previous handler results
24
+
25
+ **Returns:** Handler with `handle`, `handleAll`, and `check` methods
26
+
27
+ ### `handleResponse(response, errorCodesMap)`
28
+
29
+ Handles CQRS command responses and transforms them into validation error handlers.
30
+
31
+ **Parameters:**
32
+
33
+ - `response: ApiResponse<CommandResult<TErrors>>` - API response containing command result
34
+ - `errorCodesMap: TErrors` - Mapping of error names to numeric codes
35
+
36
+ **Returns:** Validation error handler with success/failure support
37
+
38
+ ## Usage Examples
39
+
40
+ ### Basic Error Handling
41
+
42
+ ```typescript
43
+ import { handleValidationErrors } from "@leancodepl/validation"
44
+
45
+ const errorCodes = { EmailExists: 1, InvalidEmail: 2 } as const
46
+ const errors = [
47
+ { ErrorCode: 1, ErrorMessage: "Email exists", PropertyName: "Email", AttemptedValue: "user@example.com" },
48
+ ]
49
+
50
+ handleValidationErrors(errors, errorCodes)
51
+ .handle("EmailExists", () => console.log("Email already registered"))
52
+ .handle("InvalidEmail", () => console.log("Invalid email format"))
53
+ .check()
54
+ ```
55
+
56
+ ### Command Response Handling
57
+
58
+ ```typescript
59
+ import { handleResponse } from "@leancodepl/validation"
60
+
61
+ const errorCodes = { UserNotFound: 1 } as const
62
+ const response = await fetch("/api/users/123", { method: "PUT", body: JSON.stringify({ name: "John" }) })
63
+
64
+ handleResponse(response, errorCodes)
65
+ .handle("success", () => console.log("User updated"))
66
+ .handle("UserNotFound", () => console.log("User not found"))
67
+ .handle("failure", () => console.log("Request failed"))
68
+ .check()
69
+ ```
70
+
71
+ ### Multiple Error Handling
72
+
73
+ ```typescript
74
+ import { handleValidationErrors } from "@leancodepl/validation"
75
+
76
+ const errorCodes = { Required: 1, Invalid: 2 } as const
77
+ const errors = [
78
+ { ErrorCode: 1, PropertyName: "email", ErrorMessage: "Email required" },
79
+ { ErrorCode: 2, PropertyName: "name", ErrorMessage: "Invalid name" },
80
+ ]
81
+
82
+ handleValidationErrors(errors, errorCodes)
83
+ .handleAll(["Required", "Invalid"], errorGroups => {
84
+ errorGroups.forEach(({ errors }) => {
85
+ errors.forEach(error => console.log(`${error.PropertyName}: ${error.ErrorMessage}`))
86
+ })
87
+ })
88
+ .check()
89
+ ```
90
+
91
+ ### Success/Failure Result Processing
92
+
93
+ ```typescript
94
+ import { handleResponse } from "@leancodepl/validation"
95
+
96
+ const errorCodes = { InvalidData: 1 } as const
97
+ const response = await fetch("/api/data")
98
+
99
+ const isSuccess = handleResponse(response, errorCodes)
100
+ .handle("success", () => true)
101
+ .handle(["InvalidData", "failure"], () => false)
102
+ .check({
103
+ reducer: (prev, current) => prev && current,
104
+ initialValue: true,
105
+ })
106
+ ```
package/index.cjs.js CHANGED
@@ -1,6 +1,25 @@
1
1
  'use strict';
2
2
 
3
- function handleValidationErrors(validationErrors, errorCodesMap, validationResults = []) {
3
+ /**
4
+ * Creates a validation error handler that processes errors with type-safe error code mapping.
5
+ *
6
+ * @template TAllErrors - Error codes map type extending Record<string, number>
7
+ * @template TInResult - Type of results accumulated from previous handlers
8
+ * @param validationErrors - Array of validation errors to process
9
+ * @param errorCodesMap - Mapping of error names to numeric codes
10
+ * @param validationResults - Optional array of previous handler results
11
+ * @returns Handler with handle, handleAll, and check methods
12
+ * @example
13
+ * ```typescript
14
+ * const errorCodes = { EmailExists: 1, InvalidEmail: 2 } as const;
15
+ * const errors = [{ ErrorCode: 1, ErrorMessage: 'Email exists', PropertyName: 'Email', AttemptedValue: 'test@example.com' }];
16
+ *
17
+ * handleValidationErrors(errors, errorCodes)
18
+ * .handle('EmailExists', () => console.warn('Email already registered'))
19
+ * .handle('InvalidEmail', () => console.warn('Invalid email format'))
20
+ * .check();
21
+ * ```
22
+ */ function handleValidationErrors(validationErrors, errorCodesMap, validationResults = []) {
4
23
  const handle = (validationErrorsToHandle, handler)=>{
5
24
  let result = undefined;
6
25
  for (const validationErrorToHandle of Array.isArray(validationErrorsToHandle) ? validationErrorsToHandle : [
@@ -63,7 +82,25 @@ function handleValidationErrors(validationErrors, errorCodesMap, validationResul
63
82
  };
64
83
  }
65
84
 
66
- function handleResponse(response, errorCodesMap) {
85
+ /**
86
+ * Handles CQRS command responses and transforms them into validation error handlers.
87
+ *
88
+ * @template TErrors - Error codes map type extending Record<string, number>
89
+ * @param response - API response containing command result
90
+ * @param errorCodesMap - Mapping of error names to numeric codes
91
+ * @returns Validation error handler with success/failure support
92
+ * @example
93
+ * ```typescript
94
+ * const errorCodes = { UserNotFound: 1 } as const;
95
+ * const response = await commandClient.execute(createUserCommand);
96
+ *
97
+ * handleResponse(response, errorCodes)
98
+ * .handle('success', () => console.log('User created'))
99
+ * .handle('failure', () => console.log('Network error'))
100
+ * .handle('UserNotFound', () => console.log('User not found'))
101
+ * .check();
102
+ * ```
103
+ */ function handleResponse(response, errorCodesMap) {
67
104
  const newErrorCodesMap = {
68
105
  ...errorCodesMap,
69
106
  success: -1,
package/index.esm.js CHANGED
@@ -1,4 +1,23 @@
1
- function handleValidationErrors(validationErrors, errorCodesMap, validationResults = []) {
1
+ /**
2
+ * Creates a validation error handler that processes errors with type-safe error code mapping.
3
+ *
4
+ * @template TAllErrors - Error codes map type extending Record<string, number>
5
+ * @template TInResult - Type of results accumulated from previous handlers
6
+ * @param validationErrors - Array of validation errors to process
7
+ * @param errorCodesMap - Mapping of error names to numeric codes
8
+ * @param validationResults - Optional array of previous handler results
9
+ * @returns Handler with handle, handleAll, and check methods
10
+ * @example
11
+ * ```typescript
12
+ * const errorCodes = { EmailExists: 1, InvalidEmail: 2 } as const;
13
+ * const errors = [{ ErrorCode: 1, ErrorMessage: 'Email exists', PropertyName: 'Email', AttemptedValue: 'test@example.com' }];
14
+ *
15
+ * handleValidationErrors(errors, errorCodes)
16
+ * .handle('EmailExists', () => console.warn('Email already registered'))
17
+ * .handle('InvalidEmail', () => console.warn('Invalid email format'))
18
+ * .check();
19
+ * ```
20
+ */ function handleValidationErrors(validationErrors, errorCodesMap, validationResults = []) {
2
21
  const handle = (validationErrorsToHandle, handler)=>{
3
22
  let result = undefined;
4
23
  for (const validationErrorToHandle of Array.isArray(validationErrorsToHandle) ? validationErrorsToHandle : [
@@ -61,7 +80,25 @@ function handleValidationErrors(validationErrors, errorCodesMap, validationResul
61
80
  };
62
81
  }
63
82
 
64
- function handleResponse(response, errorCodesMap) {
83
+ /**
84
+ * Handles CQRS command responses and transforms them into validation error handlers.
85
+ *
86
+ * @template TErrors - Error codes map type extending Record<string, number>
87
+ * @param response - API response containing command result
88
+ * @param errorCodesMap - Mapping of error names to numeric codes
89
+ * @returns Validation error handler with success/failure support
90
+ * @example
91
+ * ```typescript
92
+ * const errorCodes = { UserNotFound: 1 } as const;
93
+ * const response = await commandClient.execute(createUserCommand);
94
+ *
95
+ * handleResponse(response, errorCodes)
96
+ * .handle('success', () => console.log('User created'))
97
+ * .handle('failure', () => console.log('Network error'))
98
+ * .handle('UserNotFound', () => console.log('User not found'))
99
+ * .check();
100
+ * ```
101
+ */ function handleResponse(response, errorCodesMap) {
65
102
  const newErrorCodesMap = {
66
103
  ...errorCodesMap,
67
104
  success: -1,
package/package.json CHANGED
@@ -1,23 +1,54 @@
1
1
  {
2
2
  "name": "@leancodepl/validation",
3
- "version": "8.4.0",
3
+ "version": "8.5.1",
4
4
  "license": "Apache-2.0",
5
5
  "dependencies": {
6
- "@leancodepl/cqrs-client-base": "8.4.0"
6
+ "@leancodepl/cqrs-client-base": "8.5.1"
7
7
  },
8
8
  "devDependencies": {
9
9
  "sinon": "15.2.0"
10
10
  },
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "registry": "https://registry.npmjs.org/"
14
+ },
15
+ "engines": {
16
+ "node": ">=18.0.0"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/leancodepl/js_corelibrary.git",
21
+ "directory": "packages/validation"
22
+ },
23
+ "homepage": "https://github.com/leancodepl/js_corelibrary",
24
+ "bugs": {
25
+ "url": "https://github.com/leancodepl/js_corelibrary/issues"
26
+ },
27
+ "description": "CQRS validation helpers for command and query validation",
28
+ "keywords": [
29
+ "cqrs",
30
+ "validation",
31
+ "commands",
32
+ "queries",
33
+ "typescript",
34
+ "javascript",
35
+ "leancode"
36
+ ],
37
+ "author": {
38
+ "name": "LeanCode",
39
+ "url": "https://leancode.co"
40
+ },
41
+ "sideEffects": false,
11
42
  "exports": {
12
43
  "./package.json": "./package.json",
13
44
  ".": {
14
45
  "module": "./index.esm.js",
15
- "types": "./index.esm.d.ts",
46
+ "types": "./index.d.ts",
16
47
  "import": "./index.cjs.mjs",
17
48
  "default": "./index.cjs.js"
18
49
  }
19
50
  },
20
51
  "module": "./index.esm.js",
21
52
  "main": "./index.cjs.js",
22
- "types": "./index.esm.d.ts"
53
+ "types": "./index.d.ts"
23
54
  }
@@ -3,6 +3,25 @@ export type SuccessOrFailureMarker = {
3
3
  success: -1;
4
4
  failure: -2;
5
5
  };
6
+ /**
7
+ * Handles CQRS command responses and transforms them into validation error handlers.
8
+ *
9
+ * @template TErrors - Error codes map type extending Record<string, number>
10
+ * @param response - API response containing command result
11
+ * @param errorCodesMap - Mapping of error names to numeric codes
12
+ * @returns Validation error handler with success/failure support
13
+ * @example
14
+ * ```typescript
15
+ * const errorCodes = { UserNotFound: 1 } as const;
16
+ * const response = await commandClient.execute(createUserCommand);
17
+ *
18
+ * handleResponse(response, errorCodes)
19
+ * .handle('success', () => console.log('User created'))
20
+ * .handle('failure', () => console.log('Network error'))
21
+ * .handle('UserNotFound', () => console.log('User not found'))
22
+ * .check();
23
+ * ```
24
+ */
6
25
  export declare function handleResponse<TErrors extends Record<string, number>>(response: ApiResponse<CommandResult<TErrors>>, errorCodesMap: TErrors): import("./handleValidationErrors").ValidationErrorsHandler<TErrors & {
7
26
  readonly success: -1;
8
27
  readonly failure: -2;
@@ -20,4 +20,24 @@ export interface ValidationErrorsHandler<TRemainingErrors extends Record<string,
20
20
  handleAll: ValidationErrorsHandleAllFunc<TRemainingErrors, TResult>;
21
21
  check: object extends TRemainingErrors ? <TReturnValue = void>(reducer?: ReducerDescription<TResult, TReturnValue>) => TReturnValue : unknown;
22
22
  }
23
+ /**
24
+ * Creates a validation error handler that processes errors with type-safe error code mapping.
25
+ *
26
+ * @template TAllErrors - Error codes map type extending Record<string, number>
27
+ * @template TInResult - Type of results accumulated from previous handlers
28
+ * @param validationErrors - Array of validation errors to process
29
+ * @param errorCodesMap - Mapping of error names to numeric codes
30
+ * @param validationResults - Optional array of previous handler results
31
+ * @returns Handler with handle, handleAll, and check methods
32
+ * @example
33
+ * ```typescript
34
+ * const errorCodes = { EmailExists: 1, InvalidEmail: 2 } as const;
35
+ * const errors = [{ ErrorCode: 1, ErrorMessage: 'Email exists', PropertyName: 'Email', AttemptedValue: 'test@example.com' }];
36
+ *
37
+ * handleValidationErrors(errors, errorCodes)
38
+ * .handle('EmailExists', () => console.warn('Email already registered'))
39
+ * .handle('InvalidEmail', () => console.warn('Invalid email format'))
40
+ * .check();
41
+ * ```
42
+ */
23
43
  export declare function handleValidationErrors<TAllErrors extends Record<string, number>, TInResult = never>(validationErrors: ValidationError<TAllErrors>[], errorCodesMap: TAllErrors, validationResults?: TInResult[]): ValidationErrorsHandler<TAllErrors, TInResult>;
package/index.esm.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./src/index";
File without changes