Provide WsRouter to plugins
This commit is contained in:
@ -1,7 +1,10 @@
|
||||
import * as express from "express"
|
||||
import * as http from "http"
|
||||
import * as nodeFetch from "node-fetch"
|
||||
import Websocket from "ws"
|
||||
import * as util from "../src/common/util"
|
||||
import { ensureAddress } from "../src/node/app"
|
||||
import { handleUpgrade } from "../src/node/wsRouter"
|
||||
|
||||
// Perhaps an abstraction similar to this should be used in app.ts as well.
|
||||
export class HttpServer {
|
||||
@ -39,6 +42,13 @@ export class HttpServer {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Send upgrade requests to an Express app.
|
||||
*/
|
||||
public listenUpgrade(app: express.Express): void {
|
||||
handleUpgrade(app, this.hs)
|
||||
}
|
||||
|
||||
/**
|
||||
* close cleans up the server.
|
||||
*/
|
||||
@ -62,6 +72,13 @@ export class HttpServer {
|
||||
return nodeFetch.default(`${ensureAddress(this.hs)}${requestPath}`, opts)
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a websocket against the requset path.
|
||||
*/
|
||||
public ws(requestPath: string): Websocket {
|
||||
return new Websocket(`${ensureAddress(this.hs).replace("http:", "ws:")}${requestPath}`)
|
||||
}
|
||||
|
||||
public port(): number {
|
||||
const addr = this.hs.address()
|
||||
if (addr && typeof addr === "object") {
|
||||
|
@ -21,11 +21,13 @@ describe("plugin", () => {
|
||||
await papi.loadPlugins(false)
|
||||
|
||||
const app = express.default()
|
||||
papi.mount(app)
|
||||
const wsApp = express.default()
|
||||
papi.mount(app, wsApp)
|
||||
app.use("/api/applications", apps.router(papi))
|
||||
|
||||
s = new httpserver.HttpServer()
|
||||
await s.listen(app)
|
||||
s.listenUpgrade(wsApp)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
@ -70,4 +72,13 @@ describe("plugin", () => {
|
||||
const body = await resp.text()
|
||||
expect(body).toBe(indexHTML)
|
||||
})
|
||||
|
||||
it("/test-plugin/test-app (websocket)", async () => {
|
||||
const ws = s.ws("/test-plugin/test-app")
|
||||
const message = await new Promise((resolve) => {
|
||||
ws.once("message", (message) => resolve(message))
|
||||
})
|
||||
ws.terminate()
|
||||
expect(message).toBe("hello")
|
||||
})
|
||||
})
|
||||
|
@ -1,5 +1,8 @@
|
||||
import * as cs from "code-server"
|
||||
import * as fspath from "path"
|
||||
import Websocket from "ws"
|
||||
|
||||
const wss = new Websocket.Server({ noServer: true })
|
||||
|
||||
export const plugin: cs.Plugin = {
|
||||
displayName: "Test Plugin",
|
||||
@ -22,6 +25,16 @@ export const plugin: cs.Plugin = {
|
||||
return r
|
||||
},
|
||||
|
||||
wsRouter() {
|
||||
const wr = cs.WsRouter()
|
||||
wr.ws("/test-app", (req) => {
|
||||
wss.handleUpgrade(req, req.socket, req.head, (ws) => {
|
||||
ws.send("hello")
|
||||
})
|
||||
})
|
||||
return wr
|
||||
},
|
||||
|
||||
applications() {
|
||||
return [
|
||||
{
|
||||
|
Reference in New Issue
Block a user