Provide WsRouter to plugins

This commit is contained in:
Asher
2021-01-20 14:11:08 -06:00
parent fb37473e72
commit 055e0ef9ec
8 changed files with 101 additions and 34 deletions

View File

@ -1,7 +1,7 @@
import * as express from "express"
import * as expressCore from "express-serve-static-core"
import * as http from "http"
import * as net from "net"
import * as pluginapi from "../../typings/pluginapi"
export const handleUpgrade = (app: express.Express, server: http.Server): void => {
server.on("upgrade", (req, socket, head) => {
@ -20,31 +20,20 @@ export const handleUpgrade = (app: express.Express, server: http.Server): void =
})
}
export interface WebsocketRequest extends express.Request {
ws: net.Socket
head: Buffer
}
interface InternalWebsocketRequest extends WebsocketRequest {
interface InternalWebsocketRequest extends pluginapi.WebsocketRequest {
_ws_handled: boolean
}
export type WebSocketHandler = (
req: WebsocketRequest,
res: express.Response,
next: express.NextFunction,
) => void | Promise<void>
export class WebsocketRouter {
public readonly router = express.Router()
public ws(route: expressCore.PathParams, ...handlers: WebSocketHandler[]): void {
public ws(route: expressCore.PathParams, ...handlers: pluginapi.WebSocketHandler[]): void {
this.router.get(
route,
...handlers.map((handler) => {
const wrapped: express.Handler = (req, res, next) => {
;(req as InternalWebsocketRequest)._ws_handled = true
return handler(req as WebsocketRequest, res, next)
return handler(req as pluginapi.WebsocketRequest, res, next)
}
return wrapped
}),