Skip to content

Commit 68653b5

Browse files
committed
feat: new doc generation approach
1 parent ee9b65a commit 68653b5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+572
-490
lines changed

CONTRIBUTING.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,9 @@ Before you submit your Pull Request (PR) consider the following guidelines:
8383
git checkout -b my-fix-branch master
8484
```
8585

86-
1. Create your patch, **including appropriate createFeline cases**.
86+
1. Create your patch, **including appropriate test cases**.
8787
1. Follow our [Coding Rules](#rules).
88-
1. Run the full Nest createFeline suite, as described in the [developer documentation][dev-doc],
88+
1. Run the full Nest test suite, as described in the [developer documentation][dev-doc],
8989
and ensure that all tests pass.
9090
1. Commit your changes using a descriptive commit message that follows our
9191
[commit message conventions](#commit). Adherence to these conventions
@@ -105,7 +105,7 @@ Before you submit your Pull Request (PR) consider the following guidelines:
105105
1. In GitHub, send a pull request to `nestjs:master`.
106106
* If we suggest changes then:
107107
* Make the required updates.
108-
* Re-run the Nest createFeline suites to ensure tests are still passing.
108+
* Re-run the Nest test suites to ensure tests are still passing.
109109
* Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
110110

111111
```shell
@@ -205,7 +205,7 @@ Must be one of the following:
205205
* **perf**: A code change that improves performance
206206
* **refactor**: A code change that neither fixes a bug nor adds a feature
207207
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
208-
* **createFeline**: Adding missing tests or correcting existing tests
208+
* **test**: Adding missing tests or correcting existing tests
209209
210210
211211
### Subject

README.md

Lines changed: 50 additions & 145 deletions
Original file line numberDiff line numberDiff line change
@@ -25,161 +25,66 @@ $ PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true npm i --save nestjs-asyncapi
2525

2626
## Quick Start
2727

28-
Document is composed via decorators.
28+
Include AsyncApi initialization into your bootstrap function.
2929

30-
Define [AsyncApi](https://www.asyncapi.com/) service class by AsyncApiService decorator <br/>
3130
```typescript
32-
@AsyncApiService()
33-
```
34-
35-
Define publish/subscribe methods by AsyncApiPub/AsyncApiSub decorators
36-
```typescript
37-
class AnySwaggerExampleDto {
38-
@ApiProperty()
39-
readonly name: string;
40-
}
41-
42-
@AsyncApiPub({
43-
channel: 'createFeline',
44-
summary: 'Send createFeline packet',
45-
description: 'method is used for createFeline purposes',
46-
message: {
47-
name: 'createFeline data',
48-
payload: {
49-
type: AnySwaggerExampleDto,
50-
},
51-
},
52-
})
53-
54-
@AsyncApiSub({
55-
channel: 'signal',
56-
summary: 'Subscribe to signal packet',
57-
description: 'method is used for createFeline purposes',
58-
message: {
59-
name: 'createFeline data signal',
60-
payload: {
61-
type: AnySwaggerExampleDto,
62-
},
63-
},
64-
})
65-
```
66-
67-
### Usage example:
68-
69-
gateway file:
70-
```typescript
71-
import {
72-
ConnectedSocket,
73-
MessageBody,
74-
OnGatewayInit,
75-
OnGatewayDisconnect,
76-
SubscribeMessage,
77-
WebSocketGateway,
78-
WebSocketServer,
79-
} from '@nestjs/websockets';
80-
import { Namespace, Server } from 'socket.io';
81-
import { Logger } from '@nestjs/common';
82-
import { Socket } from 'socket.io-client';
83-
import { AsyncApiPub, AsyncApiService, AsyncApiSub } from 'nestjs-asyncapi';
84-
85-
@AsyncApiService()
86-
@WebSocketGateway({ transports: ['websocket'], namespace: 'cats-ws' })
87-
export class FelinesGateway implements OnGatewayInit, OnGatewayDisconnect {
88-
@WebSocketServer()
89-
server: Server;
90-
private logger: Logger = new Logger(FelinesGateway.name);
91-
92-
afterInit(nsp: Namespace) {
93-
this.logger.log(`WS server init: ${nsp?.name}`);
94-
}
95-
96-
handleDisconnect(client: Socket) {
97-
this.logger.log(`IOClient disconnected: ${client.id}`);
98-
}
99-
100-
@SubscribeMessage('createFeline')
101-
@AsyncApiPub({
102-
channel: 'createFeline',
103-
summary: 'Send createFeline packet',
104-
description: 'method is used for createFeline purposes',
105-
message: {
106-
name: 'createFeline data',
107-
payload: {
108-
type: AnySwaggerExampleDto,
109-
},
110-
},
111-
})
112-
createFeline(@ConnectedSocket() client: Socket, @MessageBody() data: string) {
113-
this.logger.log(`data from client ${client.id} : ${JSON.stringify(data)}`);
114-
this.server.emit('createFeline', data);
115-
}
116-
117-
@AsyncApiSub({
118-
channel: 'signal',
119-
summary: 'Subscribe to signal packet',
120-
description: 'method is used for createFeline purposes',
121-
message: {
122-
name: 'createFeline data signal',
123-
payload: {
124-
type: AnySwaggerExampleDto,
125-
},
126-
},
127-
})
128-
async emitCreatedFeline(boardUUID: string, data: Record<string, any>) {
129-
this.server.to('createFeline').emit('signal', data);
130-
}
131-
}
132-
133-
```
134-
135-
main file:
136-
```typescript
137-
import 'source-map-support/register';
138-
139-
import { NestFactory } from '@nestjs/core';
140-
import { NestExpressApplication } from '@nestjs/platform-express';
141-
import { AppModule } from './src/app.module';
142-
import { AsyncApiDocumentBuilder, AsyncApiModule, AsyncServerObject } from 'nestjs-asyncapi';
143-
144-
const port = 4001;
145-
const host = '0.0.0.0';
146-
const docRelPath = '/async-api';
147-
14831
async function bootstrap() {
14932
const app = await NestFactory.create<NestExpressApplication>(AppModule);
15033

151-
const asyncApiServer: AsyncServerObject = {
152-
url: 'ws://localhost:4001',
153-
protocol: 'socket.io',
154-
protocolVersion: '4',
155-
description: 'Allows you to connect using the websocket protocol to our Socket.io server.',
156-
security: [{ 'user-password': [] }],
157-
variables: {
158-
port: {
159-
description: 'Secure connection (TLS) is available through port 443.',
160-
default: '443',
161-
},
162-
},
163-
bindings: {},
164-
};
165-
16634
const asyncApiOptions = new AsyncApiDocumentBuilder()
167-
.setTitle('Cats SocketIO')
168-
.setDescription('Cats SocketIO description here')
169-
.setVersion('1.0')
170-
.setDefaultContentType('application/json')
171-
.addSecurity('user-password', { type: 'userPassword' })
172-
.addServer('cats-server', asyncApiServer)
173-
.build();
174-
35+
.setTitle('Feline')
36+
.setDescription('Feline server description here')
37+
.setVersion('1.0')
38+
.setDefaultContentType('application/json')
39+
.addSecurity('user-password', { type: 'userPassword' })
40+
.addServers({
41+
url: 'ws://localhost:3000',
42+
protocol: 'socket.io',
43+
})
44+
.build();
45+
17546
const asyncapiDocument = await AsyncApiModule.createDocument(app, asyncApiOptions);
17647
await AsyncApiModule.setup(docRelPath, app, asyncapiDocument);
17748

178-
return app.listen(port, host);
49+
// other bootstrap procedures here
50+
51+
return app.listen(3000);
52+
}
53+
```
54+
55+
AsyncApi module explores `Controllers` & `WebSocketGateway` by default.
56+
In most cases you won't need to add extra annotation,
57+
but if you need to define asyncApi operations in a class that's not a controller or gateway use `AsyncApiClass` decorator.
58+
59+
Mark pub/sub methods via `AsyncApiPub` or `AsyncApiSub` decorators<br/>
60+
61+
```typescript
62+
class CreateFelineDto {
63+
@ApiProperty()
64+
demo: string;
17965
}
18066

181-
const baseUrl = `http://${host}:${port}`;
182-
const startMessage = `Server started at ${baseUrl}; AsyncApi at ${baseUrl + docRelPath};`;
67+
@Controller()
68+
class DemoController {
69+
@AsyncApiPub({
70+
channel: 'create/feline',
71+
payload: CreateFelineDto,
72+
})
73+
async createFeline() {
74+
// logic here
75+
}
76+
77+
@AsyncApiSub({
78+
channel: 'create/feline',
79+
payload: CreateFelineDto,
80+
})
81+
async createFeline() {
82+
// logic here
83+
}
84+
}
18385

184-
bootstrap().then(() => console.log(startMessage));
18586
```
87+
88+
For more detailed examples please check out https://github.com/flamewow/nestjs-asyncapi/tree/main/sample sample app.
89+
90+
<h5>Do you use this library and like it? Don't be shy to give it a star on <a href="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/flamewow/nestjs-asyncapi">github <span style="color:yellow;">★</span></a></h3>

lib/asyncapi-document.builder.ts

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export class AsyncApiDocumentBuilder {
6969
servers: { name: string; server: AsyncServerObject }[],
7070
): this {
7171
for (const { name, server } of servers) {
72-
this.document.servers[name] = server;
72+
this.addServer(name, server);
7373
}
7474

7575
return this;
@@ -111,17 +111,6 @@ export class AsyncApiDocumentBuilder {
111111
return this;
112112
}
113113

114-
public addSecurityRequirements(
115-
name: string,
116-
requirements: string[] = [],
117-
): this {
118-
/* TODO: Check this
119-
this.document.security = (this.document.security || []).concat({
120-
[name]: requirements
121-
});*/
122-
return this;
123-
}
124-
125114
public addBearerAuth(
126115
options: SecuritySchemeObject = {
127116
type: 'http',

lib/asyncapi.constants.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const DECORATORS_PREFIX = 'asyncapi';
2+
3+
export const DECORATORS = {
4+
AsyncApiClass: `${DECORATORS_PREFIX}/class`,
5+
AsyncApiOperation: `${DECORATORS_PREFIX}/operation`,
6+
AsyncApiPub: `${DECORATORS_PREFIX}/pub`,
7+
AsyncApiSub: `${DECORATORS_PREFIX}/sub`,
8+
};

lib/binding/asyncapi.amqp.interfaces.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1-
// https://github.com/asyncapi/bindings/tree/master/amqp
1+
/**
2+
* AMPQ binding
3+
* @see https://github.com/asyncapi/bindings/tree/master/amqp
4+
*/
25

3-
export interface AmqpServerBindingObject {}
6+
/**
7+
* This object MUST NOT contain any properties. Its name is reserved for future use.
8+
*/
9+
export interface AmqpServerBinding {}
410

5-
export interface AmqpChannelBindingObject {
11+
export interface AmqpChannelBinding {
612
is: string;
713
exchange?: {
814
name: string;
@@ -21,7 +27,7 @@ export interface AmqpChannelBindingObject {
2127
bindingVersion?: string;
2228
}
2329

24-
export interface AmqpOperationBindingObject {
30+
export interface AmqpOperationBinding {
2531
expiration?: number;
2632
userId?: string;
2733
cc?: string[];
@@ -35,7 +41,7 @@ export interface AmqpOperationBindingObject {
3541
bindingVersion?: string;
3642
}
3743

38-
export interface AmqpMessageBindingObject {
44+
export interface AmqpMessageBinding {
3945
contentEncoding?: string;
4046
messageType?: string;
4147
bindingVersion?: string;
Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,35 @@
1-
// https://github.com/asyncapi/bindings/tree/master/kafka
1+
/**
2+
* Kafka binding
3+
* @see https://github.com/asyncapi/bindings/tree/master/kafka
4+
*/
25
import { SchemaObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.interface';
36

4-
export interface KafkaServerBindingObject {}
7+
export interface KafkaServerBinding {
8+
schemaRegistryUrl: string;
9+
schemaRegistryVendor: string;
10+
/**
11+
* x.y.z
12+
*/
13+
bindingVersion: string;
14+
}
515

6-
export interface KafkaChannelBindingObject {}
16+
export interface KafkaChannelBinding {
17+
topic: string;
18+
partitions: number;
19+
replicas: number;
20+
/**
21+
* x.y.z
22+
*/
23+
bindingVersion: string;
24+
}
725

8-
export interface KafkaOperationBindingObject {
26+
export interface KafkaOperationBinding {
927
groupId?: SchemaObject;
1028
clientId?: SchemaObject;
1129
bindingVersion?: string;
1230
}
1331

14-
export interface KafkaMessageBindingObject {
32+
export interface KafkaMessageBinding {
1533
key?: SchemaObject;
1634
bindingVersion?: string;
1735
}

lib/constants.ts

Lines changed: 0 additions & 7 deletions
This file was deleted.

0 commit comments

Comments
 (0)