Files
code-server/src/node/wsRouter.ts
T

55 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2020-11-05 12:58:37 -06:00
import * as express from "express"
import * as expressCore from "express-serve-static-core"
import * as http from "http"
2021-01-28 12:47:50 -06:00
import Websocket from "ws"
2021-01-20 14:11:08 -06:00
import * as pluginapi from "../../typings/pluginapi"
2020-11-05 12:58:37 -06:00
export const handleUpgrade = (app: express.Express, server: http.Server): void => {
server.on("upgrade", (req, socket, head) => {
2020-11-12 11:52:02 -06:00
socket.pause()
const wreq = req as InternalWebsocketRequest
wreq.ws = socket
wreq.head = head
wreq._ws_handled = false
2020-11-05 12:58:37 -06:00
// Send the request off to be handled by Express.
;(app as any).handle(wreq, new http.ServerResponse(wreq), () => {
if (!wreq._ws_handled) {
2020-11-10 17:52:02 -06:00
socket.end("HTTP/1.1 404 Not Found\r\n\r\n")
2020-11-05 12:58:37 -06:00
}
})
})
}
2021-01-20 14:11:08 -06:00
interface InternalWebsocketRequest extends pluginapi.WebsocketRequest {
2020-11-05 12:58:37 -06:00
_ws_handled: boolean
}
export class WebsocketRouter {
public readonly router = express.Router()
2021-01-22 11:33:16 -06:00
/**
* Handle a websocket at this route. Note that websockets are immediately
* paused when they come in.
*/
2021-01-20 14:11:08 -06:00
public ws(route: expressCore.PathParams, ...handlers: pluginapi.WebSocketHandler[]): void {
2020-11-05 12:58:37 -06:00
this.router.get(
route,
...handlers.map((handler) => {
const wrapped: express.Handler = (req, res, next) => {
;(req as InternalWebsocketRequest)._ws_handled = true
2021-01-20 14:11:08 -06:00
return handler(req as pluginapi.WebsocketRequest, res, next)
2020-11-05 12:58:37 -06:00
}
return wrapped
}),
)
}
}
export function Router(): WebsocketRouter {
return new WebsocketRouter()
}
2021-01-28 12:47:50 -06:00
// eslint-disable-next-line import/no-named-as-default-member -- the typings are not updated correctly
2021-01-28 12:47:50 -06:00
export const wss = new Websocket.Server({ noServer: true })