spooder 4.5.1 → 4.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/package.json +1 -1
- package/src/api.ts +13 -4
package/README.md
CHANGED
|
@@ -933,6 +933,10 @@ server.websocket('/path/to/websocket', {
|
|
|
933
933
|
// validates a request before it is upgraded
|
|
934
934
|
// returns HTTP 401 if FALSE is returned
|
|
935
935
|
// allows you to check headers/authentication
|
|
936
|
+
|
|
937
|
+
// if an OBJECT is returned, the object will
|
|
938
|
+
// be accessible on the websocket as ws.data.*
|
|
939
|
+
|
|
936
940
|
return true;
|
|
937
941
|
},
|
|
938
942
|
|
package/package.json
CHANGED
package/src/api.ts
CHANGED
|
@@ -104,8 +104,9 @@ export async function caution(err_message_or_obj: string | object, ...err: objec
|
|
|
104
104
|
await handle_error('caution: ', err_message_or_obj, ...err);
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
type WebsocketAcceptReturn = object | boolean;
|
|
107
108
|
type WebsocketHandlers = {
|
|
108
|
-
accept?: (req: Request) =>
|
|
109
|
+
accept?: (req: Request) => WebsocketAcceptReturn | Promise<WebsocketAcceptReturn>,
|
|
109
110
|
message?: (ws: WebSocket, message: string) => void,
|
|
110
111
|
message_json?: (ws: WebSocket, message: JsonSerializable) => void,
|
|
111
112
|
open?: (ws: WebSocket) => void,
|
|
@@ -810,10 +811,18 @@ export function serve(port: number) {
|
|
|
810
811
|
/** Add a route to upgrade connections to websockets. */
|
|
811
812
|
websocket: (path: string, handlers: WebsocketHandlers): void => {
|
|
812
813
|
routes.push([path.split('/'), async (req: Request, url: URL) => {
|
|
813
|
-
|
|
814
|
-
|
|
814
|
+
let context_data = undefined;
|
|
815
|
+
if (handlers.accept) {
|
|
816
|
+
const res = await handlers.accept(req);
|
|
817
|
+
|
|
818
|
+
if (typeof res === 'object') {
|
|
819
|
+
context_data = res;
|
|
820
|
+
} else if (!res) {
|
|
821
|
+
return 401; // Unauthorized
|
|
822
|
+
}
|
|
823
|
+
}
|
|
815
824
|
|
|
816
|
-
if (server.upgrade(req))
|
|
825
|
+
if (server.upgrade(req, { data: context_data }))
|
|
817
826
|
return 101; // Switching Protocols
|
|
818
827
|
|
|
819
828
|
return new Response('WebSocket upgrade failed', { status: 500 });
|