@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.
- package/README.md +415 -108
- package/SKILL.md +460 -0
- package/clients/custom-grpc.client.js +7 -7
- package/clients/custom-grpc.client.js.map +1 -1
- package/commands/generate-proto.command.d.ts +4 -0
- package/commands/generate-proto.command.js +33 -0
- package/commands/generate-proto.command.js.map +1 -0
- package/commands/generate-sdk.command.js.map +1 -1
- package/commands/update-ai-skill.command.d.ts +6 -0
- package/commands/update-ai-skill.command.js +117 -0
- package/commands/update-ai-skill.command.js.map +1 -0
- package/constants/metadata-key.const.d.ts +7 -0
- package/constants/metadata-key.const.js +11 -0
- package/constants/metadata-key.const.js.map +1 -0
- package/decorators/grpc-metadata.decorator.d.ts +3 -0
- package/decorators/grpc-metadata.decorator.js +28 -0
- package/decorators/grpc-metadata.decorator.js.map +1 -0
- package/decorators/grpc-param.decorator.d.ts +15 -0
- package/decorators/grpc-param.decorator.js +100 -0
- package/decorators/grpc-param.decorator.js.map +1 -0
- package/decorators/grpc-value.decorator.js +2 -3
- package/decorators/grpc-value.decorator.js.map +1 -1
- package/decorators/microservice.decorator.js +21 -6
- package/decorators/microservice.decorator.js.map +1 -1
- package/decorators/mock.decorator.d.ts +1 -0
- package/decorators/mock.decorator.js +8 -0
- package/decorators/mock.decorator.js.map +1 -1
- package/decorators/sdk-expose.decorator.d.ts +3 -0
- package/decorators/sdk-expose.decorator.js +11 -0
- package/decorators/sdk-expose.decorator.js.map +1 -0
- package/documents/grpc-test.dto.d.ts +1 -0
- package/documents/grpc-test.dto.js +5 -0
- package/documents/grpc-test.dto.js.map +1 -1
- package/documents/microservice-document.controller.js +10 -1
- package/documents/microservice-document.controller.js.map +1 -1
- package/documents/microservice-document.module.js +5 -1
- package/documents/microservice-document.module.js.map +1 -1
- package/dto/pagination.dto.d.ts +4 -0
- package/dto/pagination.dto.js +30 -0
- package/dto/pagination.dto.js.map +1 -0
- package/dto/sort.dto.d.ts +4 -0
- package/dto/sort.dto.js +32 -0
- package/dto/sort.dto.js.map +1 -0
- package/helpers/flat-param.helper.d.ts +7 -0
- package/helpers/flat-param.helper.js +88 -0
- package/helpers/flat-param.helper.js.map +1 -0
- package/helpers/grpc-method.helper.d.ts +7 -0
- package/helpers/grpc-method.helper.js +41 -0
- package/helpers/grpc-method.helper.js.map +1 -0
- package/helpers/metadata-param.helper.d.ts +1 -0
- package/helpers/metadata-param.helper.js +32 -0
- package/helpers/metadata-param.helper.js.map +1 -0
- package/helpers/mock.helper.d.ts +1 -1
- package/helpers/mock.helper.js +23 -7
- package/helpers/mock.helper.js.map +1 -1
- package/helpers/property.helper.d.ts +7 -2
- package/helpers/property.helper.js +49 -5
- package/helpers/property.helper.js.map +1 -1
- package/helpers/proto-type.helper.js +3 -0
- package/helpers/proto-type.helper.js.map +1 -1
- package/index.d.ts +3 -0
- package/index.js +3 -0
- package/index.js.map +1 -1
- package/package.json +117 -113
- package/sdk-stub/helpers/grpc.helper.d.ts +2 -0
- package/sdk-stub/helpers/grpc.helper.js +18 -6
- package/sdk-stub/helpers/grpc.helper.js.map +1 -1
- package/sdk-stub/helpers/grpc.helper.spec.ts +236 -0
- package/sdk-stub/helpers/grpc.helper.ts +23 -7
- package/sdk-stub/types/microservice-option.type.d.ts +3 -1
- package/sdk-stub/types/microservice-option.type.ts +3 -1
- package/services/generate-document.service.js +22 -20
- package/services/generate-document.service.js.map +1 -1
- package/services/generate-microservice.service.d.ts +0 -2
- package/services/generate-microservice.service.js +27 -32
- package/services/generate-microservice.service.js.map +1 -1
- package/services/generate-proto.service.d.ts +2 -0
- package/services/generate-proto.service.js +19 -3
- package/services/generate-proto.service.js.map +1 -1
- package/services/generate-skill.service.d.ts +11 -0
- package/services/generate-skill.service.js +174 -0
- package/services/generate-skill.service.js.map +1 -0
- package/services/hbs-generator.service.d.ts +1 -0
- package/services/hbs-generator.service.js +14 -0
- package/services/hbs-generator.service.js.map +1 -1
- package/services/method-template.service.d.ts +4 -2
- package/services/method-template.service.js +26 -3
- package/services/method-template.service.js.map +1 -1
- package/services/mock-method-template.service.d.ts +5 -3
- package/services/mock-method-template.service.js +19 -18
- package/services/mock-method-template.service.js.map +1 -1
- package/services/service-template.service.js +1 -1
- package/services/service-template.service.js.map +1 -1
- package/skill.json +1 -0
- package/storages/property.storage.d.ts +1 -0
- package/storages/property.storage.js +2 -1
- package/storages/property.storage.js.map +1 -1
- package/templates/body-method-template.hbs +7 -0
- package/templates/method-template.hbs +16 -6
- package/templates/mock-method-template.hbs +19 -0
- package/templates/module-template.hbs +2 -1
- package/templates/service-template.hbs +8 -0
- package/templates/skill-template.hbs +106 -0
- package/type-helpers/intersection-type.helper.js +1 -1
- package/type-helpers/intersection-type.helper.js.map +1 -1
- package/type-helpers/omit-type.helper.js +1 -1
- package/type-helpers/omit-type.helper.js.map +1 -1
- package/type-helpers/partial-type.helper.js +1 -1
- package/type-helpers/partial-type.helper.js.map +1 -1
- package/types/metadata-parameter-option.type.d.ts +6 -0
- package/types/metadata-parameter-option.type.js +3 -0
- package/types/metadata-parameter-option.type.js.map +1 -0
- package/types/parameter-option.type.d.ts +6 -0
- package/types/parameter-option.type.js +3 -0
- package/types/parameter-option.type.js.map +1 -0
- 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
|
|
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
|
-
##
|
|
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
|
-
|
|
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
|
-
|
|
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 {
|
|
52
|
+
import { Property } from '@hodfords/nestjs-grpc-helper';
|
|
53
|
+
import { IsString, IsOptional } from 'class-validator';
|
|
21
54
|
|
|
22
|
-
|
|
23
|
-
|
|
55
|
+
export class GetUserByIdDto {
|
|
56
|
+
@Property({ type: String, description: 'User id to look up' })
|
|
57
|
+
@IsString()
|
|
58
|
+
userId: string;
|
|
59
|
+
}
|
|
24
60
|
|
|
25
|
-
|
|
61
|
+
export class UserResponse {
|
|
62
|
+
@Property({ type: String, required: false })
|
|
63
|
+
@IsString()
|
|
64
|
+
@IsOptional()
|
|
65
|
+
name?: string;
|
|
26
66
|
|
|
27
|
-
|
|
67
|
+
@Property({ type: Boolean, required: false })
|
|
68
|
+
isAdmin?: boolean;
|
|
69
|
+
}
|
|
70
|
+
```
|
|
28
71
|
|
|
29
|
-
|
|
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
|
-
@
|
|
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
|
-
|
|
94
|
+
`@ResponseModel` supports single models, arrays, primitives, and nullable results:
|
|
45
95
|
|
|
46
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
57
|
-
|
|
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
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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
|
-
"
|
|
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
|
-
|
|
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
|
-
|
|
371
|
+
```shell
|
|
372
|
+
npm run wz-command make:proto sdk-config.json ./proto
|
|
373
|
+
```
|
|
101
374
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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
|
-
|
|
380
|
+
## Using a Generated SDK 📥
|
|
107
381
|
|
|
108
|
-
|
|
382
|
+
### 1. Register the SDK module
|
|
109
383
|
|
|
110
|
-
|
|
384
|
+
```typescript
|
|
385
|
+
SdkNameModule.register({
|
|
386
|
+
url: env.GRPC_URL,
|
|
387
|
+
timeout: 5000
|
|
388
|
+
});
|
|
389
|
+
```
|
|
111
390
|
|
|
112
|
-
|
|
391
|
+
Available options (`MicroserviceModuleOptionType`):
|
|
113
392
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
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
|
-
|
|
403
|
+
### 2. Inject the service and call it
|
|
122
404
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
405
|
+
```typescript
|
|
406
|
+
export class OtherService {
|
|
407
|
+
constructor(private userMicroservice: UserMicroservice) {}
|
|
126
408
|
|
|
127
|
-
|
|
128
|
-
|
|
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
|
-
|
|
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
|
|
418
|
+
### 3. Mock module for tests
|
|
137
419
|
|
|
138
|
-
|
|
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
|
-
|
|
423
|
+
```typescript
|
|
424
|
+
imports: [MockSdkNameModule];
|
|
425
|
+
```
|
|
141
426
|
|
|
142
|
-
|
|
427
|
+
## Documentation UI 🖥️
|
|
143
428
|
|
|
144
|
-
|
|
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
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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
|
-
|
|
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
|
-
|
|
455
|
+
## Custom gRPC Client 🔌
|
|
156
456
|
|
|
157
|
-
|
|
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
|
-
@
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
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
|
-
|
|
475
|
+
Generated SDK modules use it automatically.
|
|
171
476
|
|
|
172
|
-
|
|
477
|
+
## Translation Support 🌍
|
|
173
478
|
|
|
174
|
-
|
|
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
|
-
@
|
|
178
|
-
@
|
|
179
|
-
@
|
|
180
|
-
@
|
|
181
|
-
|
|
182
|
-
|
|
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
|
-
|
|
492
|
+
## AI Agent Skill 🤝
|
|
186
493
|
|
|
187
|
-
|
|
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
|
-
```
|
|
190
|
-
|
|
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
|