Skip to content

Commit

Permalink
feat: support to control websockets in a easy way
Browse files Browse the repository at this point in the history
  • Loading branch information
aralroca committed Sep 26, 2023
1 parent 2647487 commit cf0e26e
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 4 deletions.
4 changes: 3 additions & 1 deletion src/brisa/request-context/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { MatchedRoute } from "bun";
import { MatchedRoute, ServerWebSocket } from "bun";
import { I18nFromRequest } from "../../types";

export default class RequestContext extends Request {
constructor(request: Request, route?: MatchedRoute) {
super(request);
this.route = route;
this.context = new Map<string, any>();
this.ws = globalThis.ws;
}

route?: MatchedRoute;
context: Map<string, any>;
i18n?: I18nFromRequest;
ws?: ServerWebSocket<unknown>;
}
15 changes: 12 additions & 3 deletions src/cli/serve.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import importFileIfExists from "../utils/import-file-if-exists";
import getConstants from "../constants";
import handleI18n from "../utils/handle-i18n";
import redirectTrailingSlash from "../utils/redirect-trailing-slash";
import getImportableFilepath from "../utils/get-importable-filepath";

const {
IS_PRODUCTION,
Expand All @@ -22,6 +23,9 @@ const {
ASSETS_DIR,
} = getConstants();

const WEBSOCKET_PATH = getImportableFilepath("websocket", ROOT_DIR);
const wsModule = WEBSOCKET_PATH ? await import(WEBSOCKET_PATH) : null

declare global {
var ws: ServerWebSocket<unknown> | undefined;
}
Expand Down Expand Up @@ -92,13 +96,18 @@ Bun.serve({
websocket: {
open: (ws: ServerWebSocket<unknown>) => {
globalThis.ws = ws;
wsModule?.open?.(ws);
},
close: () => {
close: (...args) => {
globalThis.ws = undefined;
wsModule?.close?.(...args);
},
message: () => {
/* void */
message: (ws, message) => {
wsModule?.message?.(ws, message);
},
drain: (ws) => {
wsModule?.drain?.(ws);
}
},
});

Expand Down
1 change: 1 addition & 0 deletions src/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export interface RequestContext extends Request {
context: Map<string, any>;
route?: MatchedRoute;
i18n?: I18nFromRequest;
ws?: ServerWebSocket<unknown>;
}

type Props = Record<string, unknown> & {
Expand Down
2 changes: 2 additions & 0 deletions src/utils/load-layout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export default async function LoadLayout({
return (
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Brisa</title>
</head>
<body>{children}</body>
Expand Down

0 comments on commit cf0e26e

Please sign in to comment.