Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RegExp path support #68

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/add-ws-method.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import wrapMiddleware from './wrap-middleware';
import websocketUrl from './websocket-url';
import websocketRoute from './websocket-route';

export default function addWsMethod(target) {
/* This prevents conflict with other things setting `.ws`. */
Expand All @@ -14,7 +14,7 @@ export default function addWsMethod(target) {
* 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);
const wsRoute = websocketRoute(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
Expand Down
7 changes: 0 additions & 7 deletions src/trailing-slash.js

This file was deleted.

12 changes: 12 additions & 0 deletions src/websocket-route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Converts an express URL into a 'websocket' URL by appending .websocket
* to the path. Preserves trailing slashes and works on most RegExp routes
* as well.
* @param {string|RegExp} url express URL to modify
*/
export default function websocketRoute(url) {
if (url instanceof RegExp) {
return new RegExp(url.source.replace(/(\/)?(\$)?$/, '/.websocket$1$2'), url.flags);
}
return url.replace(/(\/)?$/, '/.websocket$1');
}
15 changes: 6 additions & 9 deletions src/websocket-url.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import trailingSlash from './trailing-slash';

/* The following fixes HenningM/express-ws#17, correctly. */
/**
* Converts a request URL into a websocket URL. Preserves trailing
* slashes and correctly handles query params and hash fragments.
* @param {string} url Request URL to process
*/
export default function websocketUrl(url) {
if (url.indexOf('?') !== -1) {
const [baseUrl, query] = url.split('?');

return `${trailingSlash(baseUrl)}.websocket?${query}`;
}
return `${trailingSlash(url)}.websocket`;
return url.replace(/(\/)?(\?.*)?$/, '/.websocket$1$2');
}