Socket IO
EzBackend uses socket.io for realtime functionality under the hood.
Accessing Socket IO
You can access the socket io instance from any EzApp
or class that extends EzApp
, for example EzBackend
From Request
You can get the non-namespaced io object from req
- Sample
- Full Sample
const socketIOtester = new EzApp()
socketIOtester.post('/hello-world', async (req, res) => {
const io = req.io
{/* Your Custom Functionality */}
})
import { EzBackend, EzModel, Type, EzApp } from '@ezbackend/common';
import { EzOpenAPI } from '@ezbackend/openapi';
import { EzDbUI } from '@ezbackend/db-ui';
import { EzCors } from '@ezbackend/cors';
const app = new EzBackend();
// ---Plugins---
// Everything is an ezapp in ezbackend
app.addApp(new EzOpenAPI());
app.addApp(new EzDbUI());
app.addApp(new EzCors());
// ---Plugins---
const socketIOtester = new EzApp()
socketIOtester.post('/hello-world', async (req, res) => {
const io = req.io
io.emit("hello", "world")
return {success: true}
})
app.addApp(socketIOtester, {prefix: 'socket-io-tester'})
app.start()
Non Namespaced
You can get the equivalent of the io object from any EzApp with
- Sample
- Full Sample
app.useSocketIORaw((io) => {/* Your Custom Functionality */})
import { EzBackend } from "@ezbackend/common"
const app = new EzBackend()
app.useSocketIORaw((io) => {
io.on("connect", (socket) => {
console.log("Client Connected: ", socket.id)
})
})
app.start()
Namespaced
An EzApp's prefix affects the namespacing of subsequent commands. the below io
instance is under the namespace /users
- Sample
- Full Sample
users.useSocketIO((io) => {/* Your Custom Functionality */})
app.addApp(users, {prefix: "users"})
import { EzBackend,EzApp } from "@ezbackend/common"
const app = new EzBackend()
const users = new EzApp()
users.useSocketIO((io) => {
io.on("connect", (socket) => {
console.log("Client Connected to Users Namespace: ", socket.id)
})
})
app.addApp(users, {prefix: "users"})
app.start()
For more information on socket io namespacing refer to the socket io docs
Why Socket IO
We chose socket.io instead of websockets or long polling because it is
- More opinionated. Socket IO comes with the concept of namespaces and rooms, meaning that you don't have to come up with your own system that is probably not as good
- Browser Support. Socket IO comes with fallbacks to long polling if the browser does not support websockets, which in turn means that EzBackend can support requests from more browsers.