@hodfords/nestjs-grpc-helper 11.4.0 → 11.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.
Files changed (116) hide show
  1. package/README.md +415 -108
  2. package/SKILL.md +460 -0
  3. package/clients/custom-grpc.client.js +7 -7
  4. package/clients/custom-grpc.client.js.map +1 -1
  5. package/commands/generate-proto.command.d.ts +4 -0
  6. package/commands/generate-proto.command.js +33 -0
  7. package/commands/generate-proto.command.js.map +1 -0
  8. package/commands/generate-sdk.command.js.map +1 -1
  9. package/commands/update-ai-skill.command.d.ts +6 -0
  10. package/commands/update-ai-skill.command.js +117 -0
  11. package/commands/update-ai-skill.command.js.map +1 -0
  12. package/constants/metadata-key.const.d.ts +7 -0
  13. package/constants/metadata-key.const.js +11 -0
  14. package/constants/metadata-key.const.js.map +1 -0
  15. package/decorators/grpc-metadata.decorator.d.ts +3 -0
  16. package/decorators/grpc-metadata.decorator.js +28 -0
  17. package/decorators/grpc-metadata.decorator.js.map +1 -0
  18. package/decorators/grpc-param.decorator.d.ts +15 -0
  19. package/decorators/grpc-param.decorator.js +100 -0
  20. package/decorators/grpc-param.decorator.js.map +1 -0
  21. package/decorators/grpc-value.decorator.js +2 -3
  22. package/decorators/grpc-value.decorator.js.map +1 -1
  23. package/decorators/microservice.decorator.js +21 -6
  24. package/decorators/microservice.decorator.js.map +1 -1
  25. package/decorators/mock.decorator.d.ts +1 -0
  26. package/decorators/mock.decorator.js +8 -0
  27. package/decorators/mock.decorator.js.map +1 -1
  28. package/decorators/sdk-expose.decorator.d.ts +3 -0
  29. package/decorators/sdk-expose.decorator.js +11 -0
  30. package/decorators/sdk-expose.decorator.js.map +1 -0
  31. package/documents/grpc-test.dto.d.ts +1 -0
  32. package/documents/grpc-test.dto.js +5 -0
  33. package/documents/grpc-test.dto.js.map +1 -1
  34. package/documents/microservice-document.controller.js +10 -1
  35. package/documents/microservice-document.controller.js.map +1 -1
  36. package/documents/microservice-document.module.js +5 -1
  37. package/documents/microservice-document.module.js.map +1 -1
  38. package/dto/pagination.dto.d.ts +4 -0
  39. package/dto/pagination.dto.js +30 -0
  40. package/dto/pagination.dto.js.map +1 -0
  41. package/dto/sort.dto.d.ts +4 -0
  42. package/dto/sort.dto.js +32 -0
  43. package/dto/sort.dto.js.map +1 -0
  44. package/helpers/flat-param.helper.d.ts +7 -0
  45. package/helpers/flat-param.helper.js +88 -0
  46. package/helpers/flat-param.helper.js.map +1 -0
  47. package/helpers/grpc-method.helper.d.ts +7 -0
  48. package/helpers/grpc-method.helper.js +41 -0
  49. package/helpers/grpc-method.helper.js.map +1 -0
  50. package/helpers/metadata-param.helper.d.ts +1 -0
  51. package/helpers/metadata-param.helper.js +32 -0
  52. package/helpers/metadata-param.helper.js.map +1 -0
  53. package/helpers/mock.helper.d.ts +1 -1
  54. package/helpers/mock.helper.js +23 -7
  55. package/helpers/mock.helper.js.map +1 -1
  56. package/helpers/property.helper.d.ts +7 -2
  57. package/helpers/property.helper.js +49 -5
  58. package/helpers/property.helper.js.map +1 -1
  59. package/helpers/proto-type.helper.js +3 -0
  60. package/helpers/proto-type.helper.js.map +1 -1
  61. package/index.d.ts +3 -0
  62. package/index.js +3 -0
  63. package/index.js.map +1 -1
  64. package/package.json +117 -113
  65. package/sdk-stub/helpers/grpc.helper.d.ts +2 -0
  66. package/sdk-stub/helpers/grpc.helper.js +18 -6
  67. package/sdk-stub/helpers/grpc.helper.js.map +1 -1
  68. package/sdk-stub/helpers/grpc.helper.spec.ts +236 -0
  69. package/sdk-stub/helpers/grpc.helper.ts +23 -7
  70. package/sdk-stub/types/microservice-option.type.d.ts +3 -1
  71. package/sdk-stub/types/microservice-option.type.ts +3 -1
  72. package/services/generate-document.service.js +22 -20
  73. package/services/generate-document.service.js.map +1 -1
  74. package/services/generate-microservice.service.d.ts +0 -2
  75. package/services/generate-microservice.service.js +27 -32
  76. package/services/generate-microservice.service.js.map +1 -1
  77. package/services/generate-proto.service.d.ts +2 -0
  78. package/services/generate-proto.service.js +19 -3
  79. package/services/generate-proto.service.js.map +1 -1
  80. package/services/generate-skill.service.d.ts +11 -0
  81. package/services/generate-skill.service.js +174 -0
  82. package/services/generate-skill.service.js.map +1 -0
  83. package/services/hbs-generator.service.d.ts +1 -0
  84. package/services/hbs-generator.service.js +14 -0
  85. package/services/hbs-generator.service.js.map +1 -1
  86. package/services/method-template.service.d.ts +4 -2
  87. package/services/method-template.service.js +26 -3
  88. package/services/method-template.service.js.map +1 -1
  89. package/services/mock-method-template.service.d.ts +5 -3
  90. package/services/mock-method-template.service.js +19 -18
  91. package/services/mock-method-template.service.js.map +1 -1
  92. package/services/service-template.service.js +1 -1
  93. package/services/service-template.service.js.map +1 -1
  94. package/skill.json +1 -0
  95. package/storages/property.storage.d.ts +1 -0
  96. package/storages/property.storage.js +2 -1
  97. package/storages/property.storage.js.map +1 -1
  98. package/templates/body-method-template.hbs +7 -0
  99. package/templates/method-template.hbs +16 -6
  100. package/templates/mock-method-template.hbs +19 -0
  101. package/templates/module-template.hbs +2 -1
  102. package/templates/service-template.hbs +8 -0
  103. package/templates/skill-template.hbs +106 -0
  104. package/type-helpers/intersection-type.helper.js +1 -1
  105. package/type-helpers/intersection-type.helper.js.map +1 -1
  106. package/type-helpers/omit-type.helper.js +1 -1
  107. package/type-helpers/omit-type.helper.js.map +1 -1
  108. package/type-helpers/partial-type.helper.js +1 -1
  109. package/type-helpers/partial-type.helper.js.map +1 -1
  110. package/types/metadata-parameter-option.type.d.ts +6 -0
  111. package/types/metadata-parameter-option.type.js +3 -0
  112. package/types/metadata-parameter-option.type.js.map +1 -0
  113. package/types/parameter-option.type.d.ts +6 -0
  114. package/types/parameter-option.type.js +3 -0
  115. package/types/parameter-option.type.js.map +1 -0
  116. package/types/sdk-build-config.type.d.ts +5 -0
package/README.md CHANGED
@@ -3,33 +3,83 @@
3
3
  </p>
4
4
 
5
5
  <p align="center">
6
- <b>nestjs-grpc-helper</b> simplifies gRPC integration in NestJS, allowing seamless communication between services. It enables easy setup of gRPC clients and servers, and supports building SDK packages that any service can import and use, ensuring consistent API interaction across your microservices architecture.
6
+ <b>nestjs-grpc-helper</b> simplifies gRPC integration in NestJS. Define your microservices with decorators, and the library generates the proto files, a fully typed TypeScript SDK, interactive documentation, and mock data keeping every consumer of your services consistent and type-safe.
7
7
  </p>
8
8
 
9
- ## Installation 🤖
9
+ ## Table of Contents 📚
10
+
11
+ - [How It Works](#how-it-works-)
12
+ - [Installation](#installation-)
13
+ - [Quick Start](#quick-start-)
14
+ - [Defining DTOs and Responses](#defining-dtos-and-responses-)
15
+ - [Decorator Reference](#decorator-reference-)
16
+ - [Type Helpers](#type-helpers-)
17
+ - [Mock Data](#mock-data-)
18
+ - [Generating an SDK](#generating-an-sdk-)
19
+ - [Using a Generated SDK](#using-a-generated-sdk-)
20
+ - [Documentation UI](#documentation-ui-)
21
+ - [Custom gRPC Client](#custom-grpc-client-)
22
+ - [Translation Support](#translation-support-)
23
+ - [AI Agent Skill](#ai-agent-skill-)
24
+ - [License](#license-)
25
+
26
+ ## How It Works 🧠
27
+
28
+ The library follows a metadata-driven code generation flow:
10
29
 
11
- Install the `nestjs-grpc-helper` package with:
30
+ 1. **Decorators** such as `@RegisterGrpcMicroservice`, `@GrpcAction`, and `@Property` attach metadata to your classes at
31
+ load time.
32
+ 2. From that metadata, the library can generate a **`.proto` file**, a **TypeScript SDK package** that other services
33
+ import for type-safe calls, an **interactive documentation UI**, and **mock implementations** for testing.
34
+
35
+ You write your service once; everything downstream is derived from it.
36
+
37
+ ## Installation 🤖
12
38
 
13
39
  ```bash
14
40
  npm install @hodfords/nestjs-grpc-helper --save
15
41
  ```
16
42
 
17
- Next, automatically generate the proto file and include it in main.ts before starting the application:
43
+ Responses must follow the [@hodfords/nestjs-response](https://www.npmjs.com/package/@hodfords/nestjs-response)
44
+ conventions, and the `make-sdk` / `update-ai-skill` commands run through
45
+ [@hodfords/nestjs-command](https://www.npmjs.com/package/@hodfords/nestjs-command).
46
+
47
+ ## Quick Start 🚀
48
+
49
+ ### 1. Define a request DTO and a response
18
50
 
19
51
  ```typescript
20
- import { generateProtoService } from '@hodfords/nestjs-grpc-helper';
52
+ import { Property } from '@hodfords/nestjs-grpc-helper';
53
+ import { IsString, IsOptional } from 'class-validator';
21
54
 
22
- generateProtoService(camelCase(env.APP_NAME), env.ROOT_PATH + '/../');
23
- ```
55
+ export class GetUserByIdDto {
56
+ @Property({ type: String, description: 'User id to look up' })
57
+ @IsString()
58
+ userId: string;
59
+ }
24
60
 
25
- ## Usage 🚀
61
+ export class UserResponse {
62
+ @Property({ type: String, required: false })
63
+ @IsString()
64
+ @IsOptional()
65
+ name?: string;
26
66
 
27
- ### Creating microservices
67
+ @Property({ type: Boolean, required: false })
68
+ isAdmin?: boolean;
69
+ }
70
+ ```
28
71
 
29
- Create microservices using the `@GrpcMicroservice` decorator, similar to how you would use a Controller. Ensure that the response adheres to the [nestjs-response](https://www.npmjs.com/package/@hodfords/nestjs-response) rules:
72
+ ### 2. Define the microservice
73
+
74
+ A gRPC microservice is declared like a controller. Each `@GrpcAction` method becomes an rpc in the generated proto and a
75
+ method in the generated SDK:
30
76
 
31
77
  ```typescript
32
- @GrpcMicroservice()
78
+ import { GrpcAction, GrpcValue, RegisterGrpcMicroservice } from '@hodfords/nestjs-grpc-helper';
79
+ import { ResponseModel } from '@hodfords/nestjs-response';
80
+
81
+ @Controller()
82
+ @RegisterGrpcMicroservice('User microservice')
33
83
  export class UserMicroservice {
34
84
  constructor(private userService: UserService) {}
35
85
 
@@ -41,160 +91,417 @@ export class UserMicroservice {
41
91
  }
42
92
  ```
43
93
 
44
- ### Any Type
94
+ `@ResponseModel` supports single models, arrays, primitives, and nullable results:
45
95
 
46
- You can use any type if fixed types are not an option. However, since it’s passed as JSON, the performance may not be as optimal as with binary. Consider using binary if performance is a concern.
96
+ ```typescript
97
+ @ResponseModel(UserResponse) // single object
98
+ @ResponseModel(UserResponse, true) // array of objects
99
+ @ResponseModel(String) // primitive (String, Number, Boolean)
100
+ @ResponseModel(UserResponse, { isAllowEmpty: true }) // object or null
101
+ ```
102
+
103
+ ### 3. Generate the proto file and start the gRPC server
104
+
105
+ Generate the proto file before the application starts, then connect the gRPC microservice:
47
106
 
48
107
  ```typescript
49
- @Property({ type: String, format: 'any', required: false })
108
+ import { generateProtoService } from '@hodfords/nestjs-grpc-helper';
109
+ import { Transport } from '@nestjs/microservices';
110
+ import path from 'path';
111
+
112
+ generateProtoService('packageName', path.join(__dirname, '../../proto'));
113
+
114
+ async function bootstrap() {
115
+ const app = await NestFactory.create(AppModule);
116
+ app.connectMicroservice<GrpcOptions>({
117
+ transport: Transport.GRPC,
118
+ options: {
119
+ url: '0.0.0.0:50059',
120
+ package: 'packageName',
121
+ protoPath: path.join(__dirname, '../../proto/microservice.proto')
122
+ }
123
+ });
124
+ await app.startAllMicroservices();
125
+ await app.listen(3000);
126
+ }
127
+ ```
128
+
129
+ ## Defining DTOs and Responses 📦
130
+
131
+ `@Property` is the single source of truth for a field. It registers the field for proto generation, SDK generation, and
132
+ Swagger documentation at the same time.
133
+
134
+ ```typescript
135
+ export class FindManyDto {
136
+ @Property({ type: 'string', description: 'Name of user to search' })
137
+ @IsString()
138
+ name: string;
139
+
140
+ @Property({ type: ParamNestedDto, isArray: true, required: true })
141
+ nestedDto: ParamNestedDto[];
142
+
143
+ @Property({ type: String, required: false, enum: UserTypeEnum, enumName: 'UserTypeEnum' })
144
+ @IsEnum(UserTypeEnum)
145
+ @IsOptional()
146
+ type?: UserTypeEnum;
147
+ }
148
+ ```
149
+
150
+ Commonly used options (all [ApiPropertyOptions](https://docs.nestjs.com/openapi/types-and-parameters) are also
151
+ accepted):
152
+
153
+ | Option | Description |
154
+ | ------------------- | ------------------------------------------------------------------------------------------- |
155
+ | `type` | `String`, `Number`, `Boolean`, a class reference, a lazy `() => Class`, or a string literal |
156
+ | `isArray` | Marks the field as repeated |
157
+ | `required` | `false` makes the field optional in the proto and SDK |
158
+ | `description` | Description used in documentation and the AI skill |
159
+ | `format` | Refines numbers (`'int32'`, `'float'`, …) or marks a string as dynamic JSON (`'any'`) |
160
+ | `enum` / `enumName` | Declares an enum field; `enumName` names the generated enum |
161
+
162
+ ### Dynamic (`any`) fields
163
+
164
+ For values without a fixed schema, combine `format: 'any'` with `@AnyType`. The value is serialized to JSON on the wire
165
+ and parsed back transparently:
166
+
167
+ ```typescript
168
+ @Property({ type: 'string', format: 'any' })
50
169
  @AnyType()
51
170
  data: any;
52
171
  ```
53
172
 
54
- ### Create SDK
173
+ ## Decorator Reference 🏷️
174
+
175
+ ### Service and method decorators
176
+
177
+ | Decorator | Description |
178
+ | ----------------------------------------- | ------------------------------------------------------------------------------------------- |
179
+ | `@RegisterGrpcMicroservice(description?)` | Marks a class as a gRPC microservice |
180
+ | `@GrpcAction(description?)` | Marks a method as a gRPC action/endpoint |
181
+ | `@SdkFlattenParams()` | Flattens the request DTO's properties into individual arguments in the generated SDK method |
182
+
183
+ ### Request parameter decorators
184
+
185
+ | Decorator | Description |
186
+ | -------------------- | ----------------------------------------------------------------------------- |
187
+ | `@GrpcValue()` | Marks a parameter as the request body (used with a DTO type) |
188
+ | `@GrpcParam(option)` | Defines a direct request parameter with name, type, and validation decorators |
189
+ | `@GrpcId(name)` | Shortcut for a required UUID string parameter (`IsNotEmpty` + `IsUUID`) |
190
+ | `@GrpcIds(name)` | Shortcut for a required array of UUID strings |
191
+ | `@GrpcEnum(option)` | Enum parameter with automatic type detection and `IsEnum` validation |
192
+ | `@GrpcEnums(option)` | Array variant of `@GrpcEnum` |
193
+ | `@GrpcPagination()` | Built-in pagination parameter (`page`, `perPage`) |
194
+ | `@GrpcSort()` | Built-in sort parameter (`sortField`, `sortDirection: 'ASC' \| 'DESC'`) |
195
+
196
+ Direct parameters can be mixed with a `@GrpcValue` body and gRPC metadata in the same method:
197
+
198
+ ```typescript
199
+ @GrpcAction('List users with pagination, sorting, and workspace scoping')
200
+ @ResponseModel(UserResponse, true)
201
+ listUsers(
202
+ @GrpcValue() param: FilterDto,
203
+ @GrpcPagination() pagination: PaginationDto,
204
+ @GrpcSort() sortParam: SortDto,
205
+ @GrpcMetadataId('workspace-id') workspaceId: string
206
+ ): Promise<UserResponse[]> { ... }
207
+ ```
208
+
209
+ ### Metadata decorators
210
+
211
+ | Decorator | Description |
212
+ | ----------------------- | -------------------------------------------------- |
213
+ | `@GrpcMetadata(option)` | Extracts a value from gRPC metadata (like headers) |
214
+ | `@GrpcMetadataId(name)` | Shortcut for a UUID metadata field |
55
215
 
56
- To generate a TypeScript SDK for your gRPC services, you can use the `make-sdk` command. This command will automatically generate the necessary proto files and package them into a JavaScript SDK.
57
- You also need the following configuration in your sdk-config.json file:
216
+ ### Property and type decorators
217
+
218
+ | Decorator | Description |
219
+ | --------------------- | ----------------------------------------------------------------------------------------- |
220
+ | `@Property(option)` | Defines a DTO/response field with type, validation, and Swagger metadata |
221
+ | `@AnyType(option?)` | JSON serialization for dynamic `any` fields (`{ isDto: true }` parses into the DTO class) |
222
+ | `@ExtendType(Parent)` | Inherits the parent's property metadata when extending a composed type |
223
+ | `@SdkExpose()` | Forces a class into the generated SDK even when no rpc references it |
224
+
225
+ ## Type Helpers 🧬
226
+
227
+ Compose DTOs while preserving the property metadata needed for proto and SDK generation. These mirror the
228
+ `@nestjs/swagger` mapped types:
229
+
230
+ ```typescript
231
+ import {
232
+ PickResponseType,
233
+ OmitResponseType,
234
+ PartialResponseType,
235
+ IntersectionResponseType
236
+ } from '@hodfords/nestjs-grpc-helper';
237
+
238
+ export class UserSummary extends PickResponseType(UserResponse, ['id', 'name']) {}
239
+ export class UserWithoutEmail extends OmitResponseType(UserResponse, ['email']) {}
240
+ export class UpdateUserDto extends PartialResponseType(UserResponse) {}
241
+ export class FullUser extends IntersectionResponseType(UserResponse, ProfileResponse) {}
242
+ ```
243
+
244
+ ## Mock Data 🎭
245
+
246
+ Mock generation powers both the documentation UI and the mock SDK module. Property-level decorators describe how each
247
+ field is faked; response-level decorators override the result of a whole method.
248
+
249
+ ### Property-level decorators
250
+
251
+ | Decorator | Description |
252
+ | ---------------------------- | -------------------------------------------- |
253
+ | `@MockMethod(method, args?)` | Generates the value with a Faker method |
254
+ | `@MockSample(value)` | Uses a fixed value |
255
+ | `@MockNested(maxSize?)` | Generates nested objects (or arrays of them) |
256
+
257
+ ```typescript
258
+ export class UserResponse {
259
+ @Property({ type: String, required: false })
260
+ @MockMethod('faker.person.firstName')
261
+ name?: string;
262
+
263
+ @Property({ type: String, enum: UserTypeEnum, enumName: 'UserTypeEnum' })
264
+ @MockSample(UserTypeEnum.STANDARD)
265
+ type: UserTypeEnum;
266
+
267
+ @Property({ type: AddressResponse, isArray: true })
268
+ @MockNested(5)
269
+ addresses: AddressResponse[];
270
+ }
271
+ ```
272
+
273
+ ### Response-level decorators
274
+
275
+ | Decorator | Description |
276
+ | ------------------------------------ | ------------------------------------------------------------------- |
277
+ | `@MockResponseSample(value)` | The mocked method returns this fixed value |
278
+ | `@MockResponseMethod(method, args?)` | The mocked method returns the result of a Faker method |
279
+ | `@MockResponseCallback(callback)` | Full control: receives the request arguments plus `(sample, model)` |
280
+
281
+ ```typescript
282
+ @GrpcAction('Check if a user is active')
283
+ @ResponseModel(Boolean)
284
+ @MockResponseSample(true)
285
+ checkUserActive(@GrpcValue() param: AnyDto): Promise<boolean> { ... }
286
+
287
+ @GrpcAction('Count users')
288
+ @ResponseModel(Number)
289
+ @MockResponseMethod('faker.number.int', [{ min: 1, max: 100 }])
290
+ countUsers(@GrpcValue() param: AnyDto): Promise<number> { ... }
291
+
292
+ @GrpcAction('Get users by name')
293
+ @ResponseModel(UserResponse, true)
294
+ @MockResponseCallback((param: AnyDto, sample, model) => sample(model))
295
+ getUsersByName(@GrpcValue() param: AnyDto): Promise<UserResponse[]> { ... }
296
+ ```
297
+
298
+ ### Generating mock instances programmatically
299
+
300
+ ```typescript
301
+ import { sample } from '@hodfords/nestjs-grpc-helper';
302
+
303
+ const mockUser = sample(UserResponse);
304
+ ```
305
+
306
+ ## Generating an SDK 🛠️
307
+
308
+ The `make-sdk` command collects every request and response type reachable from your `@GrpcAction` methods, generates the
309
+ proto file, and packages everything into a TypeScript SDK that other services install like any npm package.
310
+
311
+ Add an `sdk-config.json` to your project root:
58
312
 
59
313
  ```json
60
314
  {
61
- "name": "sdkName",
62
- "packageName": "@hodfords/package-name",
63
- "format": true,
64
- "build": true,
65
- "output": "sdk",
66
- "outputBuild": "sdkBuild",
67
- "removeOutput": true,
68
- "addAllowDecorator": true,
69
- "tsconfig": {
70
- "extends": "./tsconfig.json",
71
- "compilerOptions": {
72
- "outDir": "sdkBuild"
315
+ "name": "sdkName",
316
+ "packageName": "@hodfords/package-name",
317
+ "format": true,
318
+ "build": true,
319
+ "output": "sdk",
320
+ "outputBuild": "sdkBuild",
321
+ "removeOutput": true,
322
+ "addAllowDecorator": true,
323
+ "aiSkill": {
324
+ "name": "sdkName",
325
+ "description": "A description of the SDK"
73
326
  },
74
- "include": ["sdk"]
75
- }
327
+ "tsconfig": {
328
+ "extends": "./tsconfig.json",
329
+ "compilerOptions": {
330
+ "outDir": "sdkBuild"
331
+ },
332
+ "include": ["sdk"]
333
+ }
76
334
  }
77
335
  ```
78
- Details of the configuration:
79
-
80
- | Field | Description |
81
- |-------------------|-------------------------------------------------------|
82
- | name | Name of the SDK |
83
- | packageName | Name of the package |
84
- | format | Format the generated code |
85
- | build | Build the generated code |
86
- | output | Output directory for the generated code |
87
- | outputBuild | Output directory for the built code |
88
- | removeOutput | Remove the output directory |
89
- | addAllowDecorator | Add the allow decorator, need class-validator package |
90
- | tsconfig | TypeScript configuration |
91
336
 
337
+ | Field | Description |
338
+ | ------------------- | -------------------------------------------------------------------------------- |
339
+ | `name` | SDK name; also used as the proto package and gRPC service prefix |
340
+ | `packageName` | npm package name of the generated SDK |
341
+ | `format` | Format the generated code with Prettier |
342
+ | `build` | Compile the generated code after generation |
343
+ | `output` | Output directory for the generated source |
344
+ | `outputBuild` | Output directory for the compiled build |
345
+ | `removeOutput` | Clear the output directory before generating |
346
+ | `addAllowDecorator` | Add `@Allow()` to generated models (requires `class-validator`) |
347
+ | `tsconfig` | TypeScript configuration used to build the SDK |
348
+ | `aiSkill` | Optional. Generates `SKILL.md` and `skill.json` describing the SDK for AI agents |
349
+
350
+ Then run:
92
351
 
93
- To generate the SDK, run the following command:
94
352
  ```shell
95
353
  npm run wz-command make-sdk
96
354
  ```
97
355
 
98
- #### What this command does
356
+ The generated package contains the proto file, a typed service class per microservice, all models and enums, a dynamic
357
+ module for registration, and a mock module for testing. It is published under the name and version from your
358
+ `package.json`, and its method names, arguments, and response types match your service definitions exactly.
359
+
360
+ ### Generating only the proto file
361
+
362
+ To generate just the proto file, without building the whole SDK, use the `make:proto` command. It reuses the same
363
+ `sdk-config.json`: `name` is used as the proto package and `output` as the destination directory.
364
+
365
+ ```shell
366
+ npm run wz-command make:proto
367
+ ```
368
+
369
+ Both arguments are optional:
99
370
 
100
- This command will:
371
+ ```shell
372
+ npm run wz-command make:proto sdk-config.json ./proto
373
+ ```
101
374
 
102
- 1. **Collect all request and response types**: It gathers all `@GrpcValue` request and response types from your project.
103
- 2. **Generate proto file**: Automatically generates the necessary proto files based on the collected types.
104
- 3. **Create JavaScript Package**: Packages the generated code into a JavaScript SDK. The SDK will be published using the name and version specified in your package.json, making it available for other services to import and use. The arguments, response structure, and method names remain consistent with the definitions in your gRPC service, ensuring seamless integration and functionality across services.
375
+ | Argument | Description |
376
+ | ------------ | ----------------------------------------------------------------------------------------------------------- |
377
+ | `configFile` | Config file to read. Defaults to `sdk-config.json` |
378
+ | `outputPath` | Directory the `microservice.proto` file is written into. Defaults to the `output` field of the config file |
105
379
 
106
- ### SDK usage
380
+ ## Using a Generated SDK 📥
107
381
 
108
- After publishing the SDK, other services can easily integrate it. Here’s an example of how to use the generated SDK
382
+ ### 1. Register the SDK module
109
383
 
110
- 1. **Import the sdk package**
384
+ ```typescript
385
+ SdkNameModule.register({
386
+ url: env.GRPC_URL,
387
+ timeout: 5000
388
+ });
389
+ ```
111
390
 
112
- 2. **Register the microservice module**: Configure the microservice in `AppModule` with the appropriate gRPC URL and timeout settings.
391
+ Available options (`MicroserviceModuleOptionType`):
113
392
 
114
- ```typescript
115
- UserModule.register({
116
- url: env.GRPC_URL,
117
- timeout: 5000
118
- });
119
- ```
393
+ | Option | Description |
394
+ | ------------------------- | ------------------------------------------------------------------------ |
395
+ | `url` | gRPC server address |
396
+ | `timeout` | Request timeout in milliseconds |
397
+ | `ssl` | Use SSL credentials |
398
+ | `maxReceiveMessageLength` | Max incoming message size (default 4MB) |
399
+ | `shouldLoadEmptyArray` | Deserialize absent repeated fields as `[]` |
400
+ | `requestInitializer` | Callback to enrich the outgoing `Metadata` (auth tokens, request ids, …) |
401
+ | `…` | Any other `@grpc/grpc-js` channel option is passed through |
120
402
 
121
- 3. **Use the SDK in another service**: Import the SDK and use it to interact with your gRPC services.
403
+ ### 2. Inject the service and call it
122
404
 
123
- ```typescript
124
- export class OtherService {
125
- constructor(private userMicroservice: UserMicroservice) {}
405
+ ```typescript
406
+ export class OtherService {
407
+ constructor(private userMicroservice: UserMicroservice) {}
126
408
 
127
- async doTask(userId: string): Promise<void> {
128
- const user = await this.userMicroservice.findUserById({ id: userId });
129
- // Process user information as needed
130
- }
409
+ async doTask(userId: string): Promise<void> {
410
+ const user = await this.userMicroservice.findUserById({ userId });
131
411
  }
132
- ```
412
+ }
413
+ ```
133
414
 
134
- In this example, `OtherService` uses the `UserMicroservice` class from the SDK to call the `findUserById` method.
415
+ Calls are fully typed, request DTOs are serialized through their models, responses are transformed back into model
416
+ instances, and gRPC errors are translated into NestJS `HttpException`s (including timeouts).
135
417
 
136
- ### Mock response
418
+ ### 3. Mock module for tests
137
419
 
138
- To effectively generate and handle mock data in your application, you can use the `@MockMethod`, `@MockSample`, and `@MockNested` decorators.
420
+ Every SDK ships a mock module that provides the same service classes backed by the mock decorators no gRPC server
421
+ required:
139
422
 
140
- ##### Generate dynamic data with `@MockMethod`
423
+ ```typescript
424
+ imports: [MockSdkNameModule];
425
+ ```
141
426
 
142
- Use `@MockMethod` to apply Faker methods for generating random values.
427
+ ## Documentation UI 🖥️
143
428
 
144
- For example, to create a random string of 10 characters
429
+ The library serves an interactive UI for browsing and testing your gRPC services at
430
+ `http://your-host/microservice-documents`:
145
431
 
146
432
  ```typescript
147
- @Property({ type: String, required: false })
148
- @MockMethod('faker.datatype.string', [10])
149
- @IsString()
150
- name: string;
433
+ MicroserviceDocumentModule.register({
434
+ isEnable: env.NODE_ENV !== 'production',
435
+ packageName: 'packageName',
436
+ clientOptions: {
437
+ customClass: CustomGrpcClient,
438
+ options: {
439
+ url: '0.0.0.0:50059',
440
+ package: 'packageName',
441
+ protoPath: path.join(__dirname, '../../proto/microservice.proto')
442
+ }
443
+ }
444
+ });
151
445
  ```
152
446
 
153
- ##### Set fixed values with `@MockSample`
447
+ | Option | Description |
448
+ | --------------- | -------------------------------------------------------- |
449
+ | `isEnable` | Toggles the module (pass `false` to disable it entirely) |
450
+ | `packageName` | The proto package name |
451
+ | `clientOptions` | gRPC client options used by the "try it" feature |
452
+ | `prefix` | Optional URL prefix for the documentation routes |
453
+ | `waitingTime` | Optional delay before the client connects on startup |
154
454
 
155
- If you need to set a fixed value for a property, use the `@MockSample` decorator. This is useful for enumerations or other predefined values.
455
+ ## Custom gRPC Client 🔌
156
456
 
157
- For example, to set a fixed user type
457
+ `CustomGrpcClient` extends NestJS's `ClientGrpcProxy` with per-service client caching and support for every gRPC channel
458
+ option:
158
459
 
159
460
  ```typescript
160
- @Property({
161
- type: String,
162
- enum: UserTypeEnum,
163
- enumName: 'UserTypeEnum'
164
- })
165
- @MockSample(UserTypeEnum.STANDARD)
166
- @IsEnum(UserTypeEnum)
167
- type: UserTypeEnum;
461
+ import { CustomGrpcClient } from '@hodfords/nestjs-grpc-helper';
462
+
463
+ {
464
+ customClass: CustomGrpcClient,
465
+ options: {
466
+ maxSendMessageLength: 1024 * 1024 * 50, // 50MB max outgoing message
467
+ maxReceiveMessageLength: 1024 * 1024 * 50, // 50MB max incoming message
468
+ keepaliveTimeMs: 120000, // Keepalive ping interval
469
+ keepaliveTimeoutMs: 20000, // Keepalive timeout
470
+ keepalivePermitWithoutCalls: 1 // Allow pings without active calls
471
+ }
472
+ }
168
473
  ```
169
474
 
170
- ##### Generate nested data
475
+ Generated SDK modules use it automatically.
171
476
 
172
- Use `@MockNested` to generate mock data for nested objects or arrays of nested objects.
477
+ ## Translation Support 🌍
173
478
 
174
- For example, to create an array of 5 nested objects
479
+ Use `GrpcTranslationInterceptor` to extract the caller's language from gRPC metadata and run the handler in that
480
+ language context (via
481
+ [@hodfords/nestjs-cls-translation](https://www.npmjs.com/package/@hodfords/nestjs-cls-translation)):
175
482
 
176
483
  ```typescript
177
- @Property({ type: UserResponse, isArray: true })
178
- @IsArray()
179
- @ValidateNested()
180
- @Type(() => UserResponse)
181
- @MockNested(5)
182
- users: UserResponse[];
484
+ @UseInterceptors(GrpcTranslationInterceptor)
485
+ @GrpcAction('Get user')
486
+ @ResponseModel(UserResponse)
487
+ getUser(@GrpcValue() dto: GetUserDto): Promise<UserEntity> {
488
+ return this.userService.getUser(dto.id);
489
+ }
183
490
  ```
184
491
 
185
- ### Document for GRPC
492
+ ## AI Agent Skill 🤝
186
493
 
187
- You can go to `http://xyz/microservice-documents` to check and try to call the gRPC method
494
+ When `aiSkill` is configured in `sdk-config.json`, the generated SDK ships with a `SKILL.md` and `skill.json` that
495
+ describe your services, models, and enums in a format AI agents can consume. Consumers of the SDK can install those
496
+ skills into their project with:
188
497
 
189
- ```typescript
190
- MicroserviceDocumentModule.register({
191
- isEnable: true,
192
- prefix: <app-prefix>,
193
- packageName: camelCase(<package-name>),
194
- clientOptions: { ...microserviceGrpcConfig, customClass: CustomGrpcClient, transport: undefined }
195
- })
498
+ ```shell
499
+ npm run wz-command update-ai-skill "@hodfords/*" claude
196
500
  ```
197
501
 
502
+ The first argument is a package name pattern matched against `node_modules`; the second selects the agent — `claude`
503
+ (installs into `.claude/skills`) or `antigravity` (installs into `.agent/skills`).
504
+
198
505
  ## License 📝
199
506
 
200
507
  This project is licensed under the MIT License