-
Notifications
You must be signed in to change notification settings - Fork 140
/
add-ws-method.js
25 lines (22 loc) · 1.22 KB
/
add-ws-method.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import wrapMiddleware from './wrap-middleware';
import websocketUrl from './websocket-url';
export default function addWsMethod(target) {
/* This prevents conflict with other things setting `.ws`. */
if (target.ws === null || target.ws === undefined) {
target.ws = function addWsRoute(route, ...middlewares) {
const wrappedMiddlewares = middlewares.map(wrapMiddleware);
/* We append `/.websocket` to the route path here. Why? To prevent conflicts when
* a non-WebSocket request is made to the same GET route - after all, we are only
* interested in handling WebSocket requests.
*
* Whereas the original `express-ws` prefixed this path segment, we suffix it -
* this makes it possible to let requests propagate through Routers like normal,
* which allows us to specify WebSocket routes on Routers as well \o/! */
const wsRoute = websocketUrl(route);
/* Here we configure our new GET route. It will never get called by a client
* directly, it's just to let our request propagate internally, so that we can
* leave the regular middleware execution and error handling to Express. */
this.get.apply(this, [wsRoute].concat(wrappedMiddlewares));
};
}
}