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.
|
|
Create a new project.
|
|
Now, install support for sockets.
|
|
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 -
|
|
The generator also adds reference of the gateway file in app.module.ts
. Your app module will look like below.
|
|
Change app.gateway.ts
-
- extend AppGateway to implement
OnGatewayInit
- log a string when initialized
|
|
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.