@rexeus/typeweaver-clients 0.0.2 โ†’ 0.0.4

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 CHANGED
@@ -1,411 +1,136 @@
1
- # @rexeus/typeweaver-clients
1
+ # ๐Ÿงตโœจ @rexeus/typeweaver-clients
2
2
 
3
- HTTP client generators for TypeWeaver API specifications.
3
+ [![npm version](https://img.shields.io/npm/v/@rexeus/typeweaver-clients.svg)](https://www.npmjs.com/package/@rexeus/typeweaver-clients)
4
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
4
6
 
5
- ## Overview
7
+ Typeweaver is a type-safe HTTP API framework built for API-first development with a focus on
8
+ developer experience. Use typeweaver to specify your HTTP APIs in TypeScript and Zod, and generate
9
+ clients, validators, routers, and more โœจ
6
10
 
7
- This plugin generates type-safe HTTP API clients from your TypeWeaver API definitions, providing
8
- end-to-end type safety from API definition to client usage.
11
+ ## ๐Ÿ“ Clients Plugin
9
12
 
10
- ## Installation
13
+ This plugin generates type-safe HTTP clients from your typeweaver API definitions, providing
14
+ end-to-end type safety. The generated clients use the Command Pattern, where each API request is
15
+ encapsulated as a typed command object that contains all request data and handles response
16
+ processing.
11
17
 
12
- ```bash
13
- npm install @rexeus/typeweaver-clients
14
- ```
15
-
16
- **Peer Dependencies:**
18
+ ## ๐Ÿ“ฅ Installation
17
19
 
18
20
  ```bash
19
- npm install @rexeus/typeweaver-core @rexeus/typeweaver-gen
20
- ```
21
+ # Install the CLI and the plugin as a dev dependency
22
+ npm install -D @rexeus/typeweaver @rexeus/typeweaver-clients
21
23
 
22
- ## Usage
24
+ # Install the runtime as a dependency
25
+ npm install @rexeus/typeweaver-core
26
+ ```
23
27
 
24
- ### CLI
28
+ ## ๐Ÿ’ก How to use
25
29
 
26
30
  ```bash
27
31
  npx typeweaver generate --input ./api/definitions --output ./api/generated --plugins clients
28
32
  ```
29
33
 
30
- ### Configuration File
34
+ More on the CLI in [@rexeus/typeweaver](https://github.com/rexeus/typeweaver/tree/main/packages/cli/README.md#๏ธ-cli).
31
35
 
32
- ```javascript
33
- // typeweaver.config.js
34
- export default {
35
- input: "./api/definitions",
36
- output: "./api/generated",
37
- plugins: ["clients"],
38
- };
39
- ```
40
-
41
- ## Generated Output
36
+ ## ๐Ÿ“‚ Generated Output
42
37
 
43
- This plugin generates HTTP API clients for each entity in your API definitions.
38
+ For each resource (e.g., `Todo`), the plugin generates a HTTP client. This client can execute
39
+ request commands for all operations of this resource. This plugin generates the following files:
44
40
 
45
- ### Example Generated Client
41
+ - `<ResourceName>Client.ts` - e.g. `TodoClient.ts`
42
+ - `<OperationId>RequestCommand.ts` - e.g. `CreateTodoRequestCommand.ts`
46
43
 
47
- For an API definition with a `users` entity, the plugin generates:
44
+ ### ๐Ÿ“ก Clients
48
45
 
49
- ```typescript
50
- // UsersClient.ts
51
- import { ApiClient } from "@rexeus/typeweaver-core";
52
- import { GetUserRequestCommand } from "./GetUserRequest";
53
- import { GetUserResponseValidator } from "./GetUserResponseValidator";
54
- // ... other imports
46
+ Resource-specific HTTP clients are generated as `<ResourceName>Client.ts` files, e.g.
47
+ `TodoClient.ts`. Each client extends the `ApiClient` base class and provides:
55
48
 
56
- export class UsersClient extends ApiClient {
57
- public send(command: GetUserRequestCommand): Promise<GetUserResponse>;
58
- public send(command: CreateUserRequestCommand): Promise<CreateUserResponse>;
59
- // ... other overloads
49
+ - **Type-safe HTTP methods** - Method overloads for each operation ensuring compile-time type
50
+ checking
51
+ - **axios based** - Supports all axios features and interceptors by using custom axios instances
52
+ - **Response type mapping** - Each response is automatically mapped to the associated response class
53
+ and an instance of the class is returned. This ensures that all responses are in the defined
54
+ format and it is type-safe.
55
+ - **Unknown response handling**
56
+ - Unknown properties are automatically removed from the response. If a response exceeds the
57
+ definition, it is not rejected directly.
58
+ - If a response does not match any known format, it will be rejected by default as an
59
+ `UnknownResponse` instance.
60
+ - This unknown response handling can be configured. It is also possible for an `UnknownResponse`
61
+ instance to be created without being thrown.
60
62
 
61
- public async send(command: unknown): Promise<unknown> {
62
- if (command instanceof GetUserRequestCommand) {
63
- return this.handleGetUser(command);
64
- }
65
- if (command instanceof CreateUserRequestCommand) {
66
- return this.handleCreateUser(command);
67
- }
68
- // ... other handlers
69
-
70
- throw new Error(`Unknown command type`);
71
- }
72
-
73
- private async handleGetUser(command: GetUserRequestCommand): Promise<GetUserResponse> {
74
- const response = await this.makeRequest(command);
75
- const validator = new GetUserResponseValidator();
76
- return validator.validate(response);
77
- }
78
-
79
- // ... other private handlers
80
- }
81
- ```
82
-
83
- ## Usage Examples
84
-
85
- ### Basic Usage
63
+ **Using generated clients**
86
64
 
87
65
  ```typescript
88
- import { UsersClient } from "./api/generated/users/UsersClient";
89
- import { GetUserRequestCommand } from "./api/generated/users/GetUserRequest";
90
-
91
- const client = new UsersClient({
92
- baseURL: "https://api.example.com",
93
- });
66
+ import { TodoClient } from "path/to/generated/output";
94
67
 
95
- // Type-safe request
96
- const command = new GetUserRequestCommand({
97
- param: { userId: "123" },
98
- header: { Authorization: "Bearer token" },
68
+ const client = new TodoClient({
69
+ axiosInstance: customAxios, // Custom axios instance
70
+ baseUrl: "https://api.example.com", // Base URL for all requests
71
+ unknownResponseHandling: "throw", // "throw" | "passthrough" for unknown responses
72
+ // -> In "passthrough" mode, the received status code determines if the response is thrown
73
+ isSuccessStatusCode: code => code < 400, // Custom success status code predicate, determines whether the response is successful or should be thrown
99
74
  });
100
-
101
- try {
102
- // Fully typed response
103
- const result = await client.send(command);
104
- console.log(result.body.name); // Type-safe access
105
- } catch (error) {
106
- // Typed error handling
107
- if (error instanceof UserNotFoundErrorResponse) {
108
- console.error("User not found:", error.body.message);
109
- }
110
- }
111
75
  ```
112
76
 
113
- ### Advanced Configuration
77
+ ### โœ‰๏ธ Request Commands
114
78
 
115
- ```typescript
116
- import { UsersClient } from "./api/generated/users/UsersClient";
79
+ Request commands are generated as `<OperationId>RequestCommand.ts` files, e.g.
80
+ `CreateTodoRequestCommand.ts`. These commands encapsulate all request data and provide:
117
81
 
118
- const client = new UsersClient({
119
- baseURL: "https://api.example.com",
120
- timeout: 5000,
121
- headers: {
122
- "User-Agent": "MyApp/1.0",
123
- },
124
- // Custom axios config
125
- axios: {
126
- validateStatus: status => status < 500,
127
- },
128
- });
129
- ```
82
+ - **Type-safe construction** - Constructor enforces correct request structure
83
+ - **Complete request encapsulation** - Contains method, path, headers, query parameters, and body
84
+ - **Response processing** - Transform raw HTTP responses into typed response objects of the correct
85
+ response class
130
86
 
131
- ### Error Handling
87
+ ### Basic Usage
132
88
 
133
89
  ```typescript
134
90
  import {
135
- UsersClient,
136
- GetUserRequestCommand,
137
- UserNotFoundErrorResponse,
91
+ TodoClient,
92
+ CreateTodoRequestCommand,
93
+ CreateTodoSuccessResponse,
94
+ OtherSuccessResponse,
138
95
  ValidationErrorResponse,
139
- } from "./api/generated";
140
-
141
- const client = new UsersClient({ baseURL: "https://api.example.com" });
96
+ InternalServerErrorResponse,
97
+ } from "path/to/generated/output";
142
98
 
143
- try {
144
- const result = await client.send(
145
- new GetUserRequestCommand({
146
- param: { userId: "invalid-id" },
147
- })
148
- );
149
- } catch (error) {
150
- // Type-safe error handling
151
- if (error instanceof UserNotFoundErrorResponse) {
152
- console.error(`User not found: ${error.body.message}`);
153
- } else if (error instanceof ValidationErrorResponse) {
154
- console.error("Validation failed:", error.body.issues);
155
- } else {
156
- console.error("Unexpected error:", error);
157
- }
158
- }
159
- ```
160
-
161
- ## Client Features
162
-
163
- ### Type Safety
164
-
165
- - **Request Commands** - Fully typed request objects
166
- - **Response Types** - Typed response interfaces
167
- - **Error Types** - Typed error response classes
168
- - **Parameter Validation** - Runtime validation via Zod
169
-
170
- ### Method Overloading
171
-
172
- Each client provides method overloads for perfect type inference:
173
-
174
- ```typescript
175
- // Each command type gets its own overload
176
- client.send(getUserCommand); // Returns GetUserResponse
177
- client.send(createUserCommand); // Returns CreateUserResponse
178
- ```
179
-
180
- ### Automatic Validation
181
-
182
- - **Request validation** - Commands validate input data
183
- - **Response validation** - Responses validated against schemas
184
- - **Error parsing** - HTTP errors mapped to typed error classes
185
-
186
- ### Framework Integration
187
-
188
- Works with any HTTP client framework (uses Axios by default):
189
-
190
- ```typescript
191
- // Custom HTTP adapter
192
- const client = new UsersClient({
193
- baseURL: "https://api.example.com",
194
- httpAdapter: new FetchAdapter(), // Custom adapter
99
+ const client = new TodoClient({
100
+ baseUrl: "https://api.example.com",
195
101
  });
196
- ```
197
-
198
- ## Request Commands
199
-
200
- ### Command Structure
201
102
 
202
- Generated request commands encapsulate all request data:
203
-
204
- ```typescript
205
- import { GetUserRequestCommand } from "./GetUserRequest";
206
-
207
- const command = new GetUserRequestCommand({
208
- param: { userId: "123" }, // Path parameters
209
- query: { include: ["posts"] }, // Query parameters
210
- header: { Authorization: "Bearer token" }, // Headers
211
- body: { name: "John Doe" }, // Request body
103
+ const command = new CreateTodoRequestCommand({
104
+ header: { Authorization: "Bearer token" },
105
+ body: { title: "New Todo", status: "PENDING" },
212
106
  });
213
- ```
214
-
215
- ### Command Validation
216
107
 
217
- Commands validate input data at construction time:
218
-
219
- ```typescript
220
108
  try {
221
- const command = new GetUserRequestCommand({
222
- param: { userId: "invalid-uuid" }, // Will throw validation error
223
- });
224
- } catch (error) {
225
- console.error("Invalid command:", error.issues);
226
- }
227
- ```
228
-
229
- ## Response Handling
109
+ const response = await client.send(command);
230
110
 
231
- ### Success Responses
111
+ // If there is only one success response,
112
+ // you can directly access the response like:
113
+ console.log("Success:", response.body);
232
114
 
233
- ```typescript
234
- const result = await client.send(command);
235
-
236
- // Typed access to response data
237
- console.log(result.statusCode); // HTTP status code
238
- console.log(result.header); // Response headers
239
- console.log(result.body.id); // Response body (fully typed)
240
- ```
241
-
242
- ### Error Responses
243
-
244
- ```typescript
245
- try {
246
- const result = await client.send(command);
247
- } catch (error) {
248
- if (error instanceof UserNotFoundErrorResponse) {
249
- // Specific error type
250
- console.log(error.statusCode); // 404
251
- console.log(error.body.message); // "User not found"
115
+ // If there are multiple success responses, you can check the instance like:
116
+ if (response instanceof CreateTodoSuccessResponse) {
117
+ console.log("Todo created successfully:", response.body);
252
118
  }
253
- }
254
- ```
255
-
256
- ## Plugin Architecture
257
-
258
- This plugin extends the TypeWeaver plugin system:
259
-
260
- ```typescript
261
- import { BasePlugin, type GeneratorContext } from "@rexeus/typeweaver-gen";
262
-
263
- export default class ClientsPlugin extends BasePlugin {
264
- public name = "clients";
265
-
266
- public override generate(context: GeneratorContext): void {
267
- // Generates API clients for each entity
119
+ if (response instanceof OtherSuccessResponse) {
120
+ // ... Handle "OtherSuccessResponse"
268
121
  }
269
- }
270
- ```
271
-
272
- ## Best Practices
273
-
274
- ### Client Configuration
275
-
276
- ```typescript
277
- // Environment-specific configuration
278
- const client = new UsersClient({
279
- baseURL: process.env.API_BASE_URL,
280
- timeout: parseInt(process.env.API_TIMEOUT || "5000"),
281
- headers: {
282
- "User-Agent": `${process.env.APP_NAME}/${process.env.APP_VERSION}`,
283
- },
284
- });
285
- ```
286
-
287
- ### Error Handling Strategy
288
-
289
- ```typescript
290
- // Centralized error handling
291
- async function handleApiCall<T>(operation: () => Promise<T>): Promise<T> {
292
- try {
293
- return await operation();
294
- } catch (error) {
295
- if (error instanceof ValidationErrorResponse) {
296
- // Log validation issues
297
- logger.warn("Validation error:", error.body.issues);
298
- } else if (error instanceof UnauthorizedErrorResponse) {
299
- // Handle auth errors
300
- redirectToLogin();
301
- }
302
- throw error;
122
+ // ...
123
+ } catch (error) {
124
+ if (error instanceof ValidationErrorResponse) {
125
+ // Handle validation errors
303
126
  }
304
- }
305
-
306
- // Usage
307
- const result = await handleApiCall(() =>
308
- client.send(new GetUserRequestCommand({ param: { userId: "123" } }))
309
- );
310
- ```
311
-
312
- ### Testing
313
-
314
- ```typescript
315
- // Mock clients for testing
316
- import { UsersClient } from "./api/generated";
317
-
318
- // Mock the client
319
- jest.mock("./api/generated/users/UsersClient");
320
-
321
- const mockClient = new UsersClient() as jest.Mocked<UsersClient>;
322
- mockClient.send.mockResolvedValue({
323
- statusCode: 200,
324
- body: { id: "123", name: "Test User" },
325
- });
326
- ```
327
-
328
- ## Integration Examples
329
-
330
- ### React Hook
331
-
332
- ```typescript
333
- import { useState, useEffect } from "react";
334
- import { UsersClient, GetUserRequestCommand } from "./api/generated";
335
-
336
- const client = new UsersClient({ baseURL: "https://api.example.com" });
337
-
338
- export function useUser(userId: string) {
339
- const [user, setUser] = useState(null);
340
- const [loading, setLoading] = useState(true);
341
- const [error, setError] = useState(null);
342
-
343
- useEffect(() => {
344
- async function fetchUser() {
345
- try {
346
- setLoading(true);
347
- const result = await client.send(
348
- new GetUserRequestCommand({
349
- param: { userId },
350
- })
351
- );
352
- setUser(result.body);
353
- } catch (err) {
354
- setError(err);
355
- } finally {
356
- setLoading(false);
357
- }
358
- }
359
-
360
- fetchUser();
361
- }, [userId]);
362
-
363
- return { user, loading, error };
364
- }
365
- ```
366
-
367
- ### Node.js Service
368
-
369
- ```typescript
370
- import { UsersClient, CreateUserRequestCommand } from "./api/generated";
371
-
372
- export class UserService {
373
- private client = new UsersClient({
374
- baseURL: process.env.API_BASE_URL,
375
- });
376
-
377
- async createUser(userData: CreateUserRequest["body"]) {
378
- const command = new CreateUserRequestCommand({
379
- body: userData,
380
- header: {
381
- Authorization: `Bearer ${process.env.API_TOKEN}`,
382
- },
383
- });
384
-
385
- return await this.client.send(command);
127
+ if (error instanceof InternalServerErrorResponse) {
128
+ // Handle internal server errors
386
129
  }
130
+ // ... Handle other errors
387
131
  }
388
132
  ```
389
133
 
390
- ## Troubleshooting
391
-
392
- ### Common Issues
393
-
394
- **Import errors**: Ensure all TypeWeaver plugins are installed **Type errors**: Regenerate code
395
- after API definition changes **Runtime errors**: Check that server API matches generated client
396
- expectations
397
-
398
- ### Debug Mode
399
-
400
- Enable verbose logging:
401
-
402
- ```typescript
403
- const client = new UsersClient({
404
- baseURL: "https://api.example.com",
405
- debug: true, // Enable debug logging
406
- });
407
- ```
408
-
409
- ## License
134
+ ## ๐Ÿ“„ License
410
135
 
411
- ISC ยฉ Dennis Wentzien 2025
136
+ Apache 2.0 ยฉ Dennis Wentzien 2025