@leancodepl/axios-cqrs-client 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,111 @@
1
+ # @leancodepl/axios-cqrs-client
2
+
3
+ CQRS client with Axios for HTTP communication and command/query handling.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @leancodepl/axios-cqrs-client
9
+ # or
10
+ yarn add @leancodepl/axios-cqrs-client
11
+ ```
12
+
13
+ ## API
14
+
15
+ ### `mkCqrsClient(cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader)`
16
+
17
+ Creates CQRS client with Axios for HTTP communication and command/query handling.
18
+
19
+ **Parameters:**
20
+
21
+ - `cqrsEndpoint: string` - Base URL for CQRS API endpoints
22
+ - `tokenProvider?: TokenProvider` - Optional token provider for authentication
23
+ - `axiosOptions?: CreateAxiosDefaults` - Optional Axios configuration options
24
+ - `tokenHeader?: string` - Header name for authentication token (default: "Authorization")
25
+
26
+ **Returns:** Object with `createQuery`, `createOperation`, and `createCommand` methods
27
+
28
+ ### `mkUncapitalizedCqrsClient(params)`
29
+
30
+ Creates CQRS client with automatic response key uncapitalization using "@leancodepl/utils".
31
+
32
+ **Parameters:**
33
+
34
+ - `params: MkCqrsClientParameters` - Configuration object for CQRS client
35
+ - `params.cqrsEndpoint: string` - Base URL for CQRS API endpoints
36
+ - `params.tokenProvider?: TokenProvider` - Optional token provider for authentication
37
+ - `params.axiosOptions?: CreateAxiosDefaults` - Optional Axios configuration options
38
+ - `params.tokenHeader?: string` - Header name for authentication token (default: "Authorization")
39
+
40
+ **Returns:** CQRS client with response key transformation
41
+
42
+ ## Usage Examples
43
+
44
+ ### Basic Setup
45
+
46
+ ```typescript
47
+ import { mkCqrsClient } from "@leancodepl/axios-cqrs-client"
48
+
49
+ const client = mkCqrsClient({
50
+ cqrsEndpoint: "https://api.example.com",
51
+ tokenProvider: {
52
+ getToken: () => Promise.resolve(localStorage.getItem("token")),
53
+ invalidateToken: () => Promise.resolve(true),
54
+ },
55
+ })
56
+ ```
57
+
58
+ ### Query Operations
59
+
60
+ ```typescript
61
+ interface GetUserQuery {
62
+ userId: string
63
+ }
64
+
65
+ interface UserResult {
66
+ id: string
67
+ name: string
68
+ email: string
69
+ }
70
+
71
+ const getUser = client.createQuery<GetUserQuery, UserResult>("GetUser")
72
+
73
+ const response = await getUser({ userId: "123" })
74
+
75
+ if (response.isSuccess) {
76
+ console.log("User:", response.result)
77
+ }
78
+ ```
79
+
80
+ ### Command Operations
81
+
82
+ ```typescript
83
+ interface CreateUserCommand {
84
+ name: string
85
+ email: string
86
+ }
87
+
88
+ const errorCodes = { EmailExists: 1, InvalidEmail: 2 } as const
89
+ const createUser = client.createCommand<CreateUserCommand, typeof errorCodes>("CreateUser", errorCodes)
90
+
91
+ const response = await createUser({ name: "John", email: "john@example.com" })
92
+
93
+ createUser
94
+ .handle({ name: "John", email: "john@example.com" })
95
+ .handle("success", () => console.log("User created"))
96
+ .handle("EmailExists", () => console.log("Email already exists"))
97
+ .check()
98
+ ```
99
+
100
+ ### Uncapitalized Client
101
+
102
+ ```typescript
103
+ import { mkUncapitalizedCqrsClient } from "@leancodepl/axios-cqrs-client"
104
+
105
+ const client = mkUncapitalizedCqrsClient({
106
+ cqrsEndpoint: "https://api.example.com",
107
+ })
108
+
109
+ // Automatically transforms { UserId: '123' } to { userId: '123' }
110
+ const response = await client.createQuery("GetUser")({ userId: "123" })
111
+ ```
package/index.cjs.js CHANGED
@@ -21,13 +21,33 @@ function createSuccess(result) {
21
21
  result
22
22
  };
23
23
  }
24
- function createError(error) {
24
+ function createError(error, options) {
25
25
  return {
26
26
  isSuccess: false,
27
+ isAborted: !!(options == null ? void 0 : options.isAborted),
27
28
  error
28
29
  };
29
30
  }
30
- function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader = "Authorization" }) {
31
+ /**
32
+ * Creates CQRS client with Axios for HTTP communication and command/query handling.
33
+ *
34
+ * Provides type-safe methods for creating queries, operations, and commands with automatic
35
+ * token management, retry logic, and response handling. Supports validation error handling
36
+ * and HTTP status code management.
37
+ *
38
+ * @param cqrsEndpoint - Base URL for CQRS API endpoints
39
+ * @param tokenProvider - Optional token provider for authentication
40
+ * @param axiosOptions - Optional Axios configuration options
41
+ * @param tokenHeader - Header name for authentication token (default: "Authorization")
42
+ * @returns Object with `createQuery`, `createOperation`, and `createCommand` methods
43
+ * @example
44
+ * ```typescript
45
+ * const client = mkCqrsClient({
46
+ * cqrsEndpoint: 'https://api.example.com',
47
+ * tokenProvider: { getToken: () => Promise.resolve('token') }
48
+ * });
49
+ * ```
50
+ */ function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader = "Authorization" }) {
31
51
  const apiAxios = axios.create(_extends({
32
52
  baseURL: cqrsEndpoint
33
53
  }, axiosOptions));
@@ -43,13 +63,31 @@ function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader =
43
63
  response.data = createSuccess(response.data);
44
64
  return response;
45
65
  }, async (error)=>{
66
+ if (!(error instanceof axios.AxiosError)) {
67
+ return {
68
+ data: createError(`Unknown error ${error}`)
69
+ };
70
+ }
71
+ if (error.code === "ERR_CANCELED") {
72
+ return {
73
+ data: createError(error, {
74
+ isAborted: true
75
+ })
76
+ };
77
+ }
78
+ if (!error.response) {
79
+ return {
80
+ data: createError(error)
81
+ };
82
+ }
46
83
  const response = error.response;
47
84
  switch(error.response.status){
48
85
  case 401:
49
86
  {
50
87
  var _config_params;
51
- const config = error.config;
52
- if ((_config_params = config.params) == null ? void 0 : _config_params.isRetry) {
88
+ var _config;
89
+ let config = error.config;
90
+ if (config == null ? void 0 : (_config_params = config.params) == null ? void 0 : _config_params.isRetry) {
53
91
  response.data = createError("The request has not been authorized and token refresh did not help");
54
92
  break;
55
93
  }
@@ -61,7 +99,11 @@ function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader =
61
99
  response.data = createError("Cannot refresh access token after the server returned 401 Unauthorized");
62
100
  break;
63
101
  }
64
- config.params = error.config.params || {};
102
+ config != null ? config : config = {
103
+ headers: new axios.AxiosHeaders()
104
+ };
105
+ var _params;
106
+ (_params = (_config = config).params) != null ? _params : _config.params = {};
65
107
  config.params.isRetry = true;
66
108
  return await apiAxios.request(config);
67
109
  }
@@ -116,7 +158,25 @@ function uncapitalizeResponse(response) {
116
158
  result: utils.uncapitalizeDeep(response.result)
117
159
  });
118
160
  }
119
- function mkUncapitalizedCqrsClient(params) {
161
+ /**
162
+ * Creates CQRS client with automatic response key uncapitalization using "@leancodepl/utils".
163
+ *
164
+ * Extends the base CQRS client to automatically transform response object keys from
165
+ * PascalCase to camelCase using deep transformation.
166
+ *
167
+ * @param params - Configuration object for CQRS client
168
+ * @param params.cqrsEndpoint - Base URL for CQRS API endpoints
169
+ * @param params.tokenProvider - Optional token provider for authentication
170
+ * @param params.axiosOptions - Optional Axios configuration options
171
+ * @param params.tokenHeader - Header name for authentication token (default: "Authorization")
172
+ * @returns CQRS client with response key transformation
173
+ * @example
174
+ * ```typescript
175
+ * const client = mkUncapitalizedCqrsClient({
176
+ * cqrsEndpoint: 'https://api.example.com'
177
+ * });
178
+ * ```
179
+ */ function mkUncapitalizedCqrsClient(params) {
120
180
  const baseClient = mkCqrsClient(params);
121
181
  return _extends({}, baseClient, {
122
182
  createQuery (type) {
package/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import axios from 'axios';
1
+ import axios, { AxiosError, AxiosHeaders } from 'axios';
2
2
  import { handleResponse } from '@leancodepl/validation';
3
3
  import { uncapitalizeDeep } from '@leancodepl/utils';
4
4
 
@@ -19,13 +19,33 @@ function createSuccess(result) {
19
19
  result
20
20
  };
21
21
  }
22
- function createError(error) {
22
+ function createError(error, options) {
23
23
  return {
24
24
  isSuccess: false,
25
+ isAborted: !!(options == null ? void 0 : options.isAborted),
25
26
  error
26
27
  };
27
28
  }
28
- function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader = "Authorization" }) {
29
+ /**
30
+ * Creates CQRS client with Axios for HTTP communication and command/query handling.
31
+ *
32
+ * Provides type-safe methods for creating queries, operations, and commands with automatic
33
+ * token management, retry logic, and response handling. Supports validation error handling
34
+ * and HTTP status code management.
35
+ *
36
+ * @param cqrsEndpoint - Base URL for CQRS API endpoints
37
+ * @param tokenProvider - Optional token provider for authentication
38
+ * @param axiosOptions - Optional Axios configuration options
39
+ * @param tokenHeader - Header name for authentication token (default: "Authorization")
40
+ * @returns Object with `createQuery`, `createOperation`, and `createCommand` methods
41
+ * @example
42
+ * ```typescript
43
+ * const client = mkCqrsClient({
44
+ * cqrsEndpoint: 'https://api.example.com',
45
+ * tokenProvider: { getToken: () => Promise.resolve('token') }
46
+ * });
47
+ * ```
48
+ */ function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader = "Authorization" }) {
29
49
  const apiAxios = axios.create(_extends({
30
50
  baseURL: cqrsEndpoint
31
51
  }, axiosOptions));
@@ -41,13 +61,31 @@ function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader =
41
61
  response.data = createSuccess(response.data);
42
62
  return response;
43
63
  }, async (error)=>{
64
+ if (!(error instanceof AxiosError)) {
65
+ return {
66
+ data: createError(`Unknown error ${error}`)
67
+ };
68
+ }
69
+ if (error.code === "ERR_CANCELED") {
70
+ return {
71
+ data: createError(error, {
72
+ isAborted: true
73
+ })
74
+ };
75
+ }
76
+ if (!error.response) {
77
+ return {
78
+ data: createError(error)
79
+ };
80
+ }
44
81
  const response = error.response;
45
82
  switch(error.response.status){
46
83
  case 401:
47
84
  {
48
85
  var _config_params;
49
- const config = error.config;
50
- if ((_config_params = config.params) == null ? void 0 : _config_params.isRetry) {
86
+ var _config;
87
+ let config = error.config;
88
+ if (config == null ? void 0 : (_config_params = config.params) == null ? void 0 : _config_params.isRetry) {
51
89
  response.data = createError("The request has not been authorized and token refresh did not help");
52
90
  break;
53
91
  }
@@ -59,7 +97,11 @@ function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader =
59
97
  response.data = createError("Cannot refresh access token after the server returned 401 Unauthorized");
60
98
  break;
61
99
  }
62
- config.params = error.config.params || {};
100
+ config != null ? config : config = {
101
+ headers: new AxiosHeaders()
102
+ };
103
+ var _params;
104
+ (_params = (_config = config).params) != null ? _params : _config.params = {};
63
105
  config.params.isRetry = true;
64
106
  return await apiAxios.request(config);
65
107
  }
@@ -114,7 +156,25 @@ function uncapitalizeResponse(response) {
114
156
  result: uncapitalizeDeep(response.result)
115
157
  });
116
158
  }
117
- function mkUncapitalizedCqrsClient(params) {
159
+ /**
160
+ * Creates CQRS client with automatic response key uncapitalization using "@leancodepl/utils".
161
+ *
162
+ * Extends the base CQRS client to automatically transform response object keys from
163
+ * PascalCase to camelCase using deep transformation.
164
+ *
165
+ * @param params - Configuration object for CQRS client
166
+ * @param params.cqrsEndpoint - Base URL for CQRS API endpoints
167
+ * @param params.tokenProvider - Optional token provider for authentication
168
+ * @param params.axiosOptions - Optional Axios configuration options
169
+ * @param params.tokenHeader - Header name for authentication token (default: "Authorization")
170
+ * @returns CQRS client with response key transformation
171
+ * @example
172
+ * ```typescript
173
+ * const client = mkUncapitalizedCqrsClient({
174
+ * cqrsEndpoint: 'https://api.example.com'
175
+ * });
176
+ * ```
177
+ */ function mkUncapitalizedCqrsClient(params) {
118
178
  const baseClient = mkCqrsClient(params);
119
179
  return _extends({}, baseClient, {
120
180
  createQuery (type) {
package/package.json CHANGED
@@ -1,22 +1,55 @@
1
1
  {
2
2
  "name": "@leancodepl/axios-cqrs-client",
3
- "version": "8.4.0",
3
+ "version": "8.5.1",
4
4
  "license": "Apache-2.0",
5
+ "publishConfig": {
6
+ "access": "public",
7
+ "registry": "https://registry.npmjs.org/"
8
+ },
9
+ "engines": {
10
+ "node": ">=18.0.0"
11
+ },
5
12
  "dependencies": {
6
- "@leancodepl/cqrs-client-base": "8.4.0",
7
- "@leancodepl/validation": "8.4.0",
13
+ "@leancodepl/cqrs-client-base": "8.5.1",
14
+ "@leancodepl/validation": "8.5.1",
8
15
  "axios": ">=1.6.0"
9
16
  },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/leancodepl/js_corelibrary.git",
20
+ "directory": "packages/cqrs-clients/axios-cqrs-client"
21
+ },
22
+ "homepage": "https://github.com/leancodepl/js_corelibrary",
23
+ "bugs": {
24
+ "url": "https://github.com/leancodepl/js_corelibrary/issues"
25
+ },
26
+ "description": "HTTP CQRS client implementation using Axios",
27
+ "keywords": [
28
+ "cqrs",
29
+ "http",
30
+ "axios",
31
+ "commands",
32
+ "queries",
33
+ "api",
34
+ "typescript",
35
+ "javascript",
36
+ "leancode"
37
+ ],
38
+ "author": {
39
+ "name": "LeanCode",
40
+ "url": "https://leancode.co"
41
+ },
42
+ "sideEffects": false,
10
43
  "exports": {
11
44
  "./package.json": "./package.json",
12
45
  ".": {
13
46
  "module": "./index.esm.js",
14
- "types": "./index.esm.d.ts",
47
+ "types": "./index.d.ts",
15
48
  "import": "./index.cjs.mjs",
16
49
  "default": "./index.cjs.js"
17
50
  }
18
51
  },
19
52
  "module": "./index.esm.js",
20
53
  "main": "./index.cjs.js",
21
- "types": "./index.esm.d.ts"
54
+ "types": "./index.d.ts"
22
55
  }
@@ -6,6 +6,26 @@ export type MkCqrsClientParameters = {
6
6
  axiosOptions?: CreateAxiosDefaults;
7
7
  tokenHeader?: string;
8
8
  };
9
+ /**
10
+ * Creates CQRS client with Axios for HTTP communication and command/query handling.
11
+ *
12
+ * Provides type-safe methods for creating queries, operations, and commands with automatic
13
+ * token management, retry logic, and response handling. Supports validation error handling
14
+ * and HTTP status code management.
15
+ *
16
+ * @param cqrsEndpoint - Base URL for CQRS API endpoints
17
+ * @param tokenProvider - Optional token provider for authentication
18
+ * @param axiosOptions - Optional Axios configuration options
19
+ * @param tokenHeader - Header name for authentication token (default: "Authorization")
20
+ * @returns Object with `createQuery`, `createOperation`, and `createCommand` methods
21
+ * @example
22
+ * ```typescript
23
+ * const client = mkCqrsClient({
24
+ * cqrsEndpoint: 'https://api.example.com',
25
+ * tokenProvider: { getToken: () => Promise.resolve('token') }
26
+ * });
27
+ * ```
28
+ */
9
29
  export declare function mkCqrsClient({ cqrsEndpoint, tokenProvider, axiosOptions, tokenHeader, }: MkCqrsClientParameters): {
10
30
  createQuery<TQuery, TResult>(type: string): (dto: TQuery) => QueryPromise<TResult>;
11
31
  createOperation<TOperation, TResult>(type: string): (dto: TOperation) => Promise<ApiError | ApiSuccess<TResult>>;
@@ -1,5 +1,24 @@
1
1
  import type { ApiResponse } from "@leancodepl/cqrs-client-base";
2
2
  import { type MkCqrsClientParameters } from "./mkCqrsClient";
3
+ /**
4
+ * Creates CQRS client with automatic response key uncapitalization using "@leancodepl/utils".
5
+ *
6
+ * Extends the base CQRS client to automatically transform response object keys from
7
+ * PascalCase to camelCase using deep transformation.
8
+ *
9
+ * @param params - Configuration object for CQRS client
10
+ * @param params.cqrsEndpoint - Base URL for CQRS API endpoints
11
+ * @param params.tokenProvider - Optional token provider for authentication
12
+ * @param params.axiosOptions - Optional Axios configuration options
13
+ * @param params.tokenHeader - Header name for authentication token (default: "Authorization")
14
+ * @returns CQRS client with response key transformation
15
+ * @example
16
+ * ```typescript
17
+ * const client = mkUncapitalizedCqrsClient({
18
+ * cqrsEndpoint: 'https://api.example.com'
19
+ * });
20
+ * ```
21
+ */
3
22
  export declare function mkUncapitalizedCqrsClient(params: MkCqrsClientParameters): {
4
23
  createQuery<TQuery, TResult>(type: string): (dto: TQuery) => Promise<import("@leancodepl/cqrs-client-base").ApiError | {
5
24
  result: import("@leancodepl/utils").TransformDeep<TResult, "uncapitalize">;
@@ -13,7 +32,7 @@ export declare function mkUncapitalizedCqrsClient(params: MkCqrsClientParameters
13
32
  [name: string]: number;
14
33
  }>(type: string, errorCodesMap: TErrorCodes): {
15
34
  (dto: TCommand): Promise<ApiResponse<import("@leancodepl/cqrs-client-base").CommandResult<TErrorCodes>>>;
16
- handle(dto: TCommand): Promise<import("dist/packages/validation/src").ValidationErrorsHandler<TErrorCodes & {
35
+ handle(dto: TCommand): Promise<import("@leancodepl/validation").ValidationErrorsHandler<TErrorCodes & {
17
36
  readonly success: -1;
18
37
  readonly failure: -2;
19
38
  }, never>>;
package/index.esm.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./src/index";
File without changes