Reputation: 85
I have been searching for a few days now but still haven’t found any alternative or help writing a TypeScript Declaration for it as I also tried that.
https://www.npmjs.com/package/express-ws
Important is that it works with any other route in express. Authentication, Roles and Path Parameters.
Upvotes: 4
Views: 9230
Reputation: 79
Thanks Derek Hill and Normunds Kalnberzins
Works with routers is better
First import express-ws
import expressWs from 'express-ws';
To use the ws
method, you need to strengthen express (I understand it this way)
const { app, getWss, applyTo } = expressWs(express());
after that
express.Router
contains the ws
method, but the type of the typescript is wrong, you only need to convert the type.
const router = express.Router() as expressWs.Router;
Define the routing logic
router.ws('/echo', (ws, req) => {
ws.on('message', (msg: String) => {
ws.send(msg);
});
});
Finally add router
to the express app
app.use("/ws-stuff", router);
Upvotes: 7
Reputation: 6454
Typings for express-ws have now been created.
The tests show how to use it:
import expressWs from 'express-ws';
const { app, getWss, applyTo } = expressWs(express());
Or:
const app = expressWs(express()).app;
Then for example when declaring routes rather than writing:
const myRoutes = function(app: Express) {...}
You need to specify the express-ws type:
import expressWs from 'express-ws';
const myRoutes = function(app: expressWs.Application) {...}
Upvotes: 11
Reputation: 1245
The only problem is that Router
type has no ws(...)
method. Add
export interface RouterWs extends express.Router {
ws (route: string, ...cb): RouterWs;
}
Then later when getting Router
just cast it as your type.
const router = express.Router() as RouterWs;
router.ws('/somepath', (ws, req) => {...
Upvotes: 2