Send live updates with WebSockets
12.6.0
Keep a connection open when the server needs to send live changes to the browser.
On this page
Create a Socket.IO gateway
Install @nestjs/websockets and @nestjs/platform-socket.io. Add the gateway to module providers. The example handles a ping and returns an acknowledgement. A browser using the Socket.IO adapter also needs its matching client package, socket.io-client.
import { SubscribeMessage, WebSocketGateway } from "@nestjs/websockets";
@WebSocketGateway()
export class InventoryGateway {
@SubscribeMessage("inventory:ping")
ping() {
return { status: "ok" };
}
}
// Browser client, served from the same origin
// import { io } from "socket.io-client";
// const socket = io();
// socket.timeout(3000).emit("inventory:ping", (error, reply) => {
// if (error) console.error("No reply");
// else console.log(reply.status);
// });
Send stock changes after they are saved
For live inventory, authenticate each connection and check access before joining a shop room. After a database commit, send an event to that room. When a client reconnects, reload the list from the API so it can catch up on changes it may have missed.
// In an authorized update handler. The shop ID comes from the session.
const change = await this.dataSource.transaction(async manager => {
const products = manager.getRepository(Product);
const product = await products.findOneByOrFail({ id: productId, shopId });
product.quantity = quantity;
const saved = await products.save(product);
return { id: saved.id, quantity: saved.quantity };
});
this.server.to("shop:" + shopId).emit("inventory:updated", change);
// Browser: "connect" also fires after reconnecting.
socket.on("connect", reloadInventory);