NestJS is one of the things I have been playing around a bit in the recent days. Here’s how you can create a websocket application quickly on NestJS.
Did I say this is a sample app that serves no real-world value other than poking around the application?
Setup project in NestJS
First.. install NextJS if you have not done so.
1
|
yarn global add @nestjs/cli
|
Create a new project.
1
|
nest new websocket-proj
|
Now, install support for sockets.
1
2
3
4
|
cd websocket-proj
yarn add -D @types/socket.io
yarn add @nestjs/websockets @nestjs/platform-socket.io
|
Open the folder websocket-proj
in VS Code. We can delete everything in the src
folder except app.module.ts
and main.ts
.
Add websocket functions
Add an app gateway using Nest CLI.
This adds two files app.gateway.spec.ts
and app.gateway.ts
. The latter looks like the below -
1
2
3
4
5
6
7
8
9
10
11
|
import { SubscribeMessage, WebSocketGateway } from "@nestjs/websockets";
import { Logger } from "@nestjs/common";
@WebSocketGateway()
export class AppGateway implements OnGatewayInit {
// export class AppGateway {
@SubscribeMessage("message")
handleMessage(client: any, payload: any): string {
return "Hello world!";
}
}
|
The generator also adds reference of the gateway file in app.module.ts
. Your app module will look like below.
1
2
3
4
5
6
7
8
9
|
import { Module } from "@nestjs/common";
import { AppGateway } from "./app.gateway";
@Module({
imports: [],
controllers: [],
providers: [AppGateway],
})
export class AppModule {}
|
Change app.gateway.ts
-
- extend AppGateway to implement
OnGatewayInit
- log a string when initialized
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
} from "@nestjs/websockets";
import { Logger } from "@nestjs/common";
@WebSocketGateway(3001)
export class AppGateway implements OnGatewayInit {
private logger: Logger = new Logger("AppGateway");
afterInit(server: any) {
// throw new Error('Method not implemented.'); - comment this
this.logger.log("Initialized");
}
// export class AppGateway {
@SubscribeMessage("message")
handleMessage(client: any, payload: any): string {
return "Hello world!";
}
}
|
Start server in dev mode.
The server starts and you see this beautiful message.
You could now use any web socket client to subscribe to a message on port 3001 and get “hello world” back.