11import { z , createRoute , OpenAPIHono } from "@hono/zod-openapi" ;
22import { serve } from "@hono/node-server" ;
3+ import { createNodeWebSocket } from "@hono/node-ws" ;
34import { getUserTodoStore } from "./todo" ;
45import { cors } from "hono/cors" ;
56import { assert } from "tsafe/assert" ;
6- import { getUser , bootstrapAuth } from "./auth" ;
7+ import { bootstrapAuth , getUser , getUser_ws } from "./auth" ;
78
89( async function main ( ) {
9-
1010 const issuerUri = ( ( ) => {
1111 const value = process . env . OIDC_ISSUER_URI ;
1212
@@ -33,6 +33,25 @@ import { getUser, bootstrapAuth } from "./auth";
3333
3434 app . use ( "*" , cors ( ) ) ;
3535
36+ const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket ( { app } ) ;
37+
38+ app . get (
39+ "/ws" ,
40+ upgradeWebSocket ( async c => {
41+
42+ const user = await getUser_ws ( { req : c . req } ) ;
43+
44+ return {
45+ onOpen : ( _event , ws ) => {
46+ ws . send ( `Hello ${ user . name } ` ) ;
47+ } ,
48+ onMessage ( event , ws ) {
49+ ws . send ( `I'm not very smart, all I can do is repeat what you say: "${ event . data } "` ) ;
50+ }
51+ } ;
52+ } )
53+ ) ;
54+
3655 {
3756 const route = createRoute ( {
3857 method : "put" ,
@@ -88,8 +107,7 @@ import { getUser, bootstrapAuth } from "./auth";
88107 } ) ;
89108
90109 app . openapi ( route , async c => {
91-
92- const user = await getUser ( c . req ) ;
110+ const user = await getUser ( { req : c . req } ) ;
93111
94112 const { id } = c . req . valid ( "param" ) ;
95113 const { text, isDone } = c . req . valid ( "json" ) ;
@@ -158,7 +176,7 @@ import { getUser, bootstrapAuth } from "./auth";
158176 } ) ;
159177
160178 app . openapi ( route , async c => {
161- const user = await getUser ( c . req ) ;
179+ const user = await getUser ( { req : c . req } ) ;
162180
163181 const { text } = c . req . valid ( "json" ) ;
164182
@@ -207,7 +225,7 @@ import { getUser, bootstrapAuth } from "./auth";
207225 } ) ;
208226
209227 app . openapi ( route , async c => {
210- const user = await getUser ( c . req ) ;
228+ const user = await getUser ( { req : c . req } ) ;
211229
212230 const todos = getUserTodoStore ( user . id ) . getAll ( ) ;
213231
@@ -241,8 +259,8 @@ import { getUser, bootstrapAuth } from "./auth";
241259 } ) ;
242260
243261 app . openapi ( route , async c => {
244- const user = await getUser ( c . req ) ;
245-
262+ const user = await getUser ( { req : c . req } ) ;
263+
246264 const { id } = c . req . valid ( "param" ) ;
247265
248266 getUserTodoStore ( user . id ) . remove ( id ) ;
@@ -269,11 +287,13 @@ import { getUser, bootstrapAuth } from "./auth";
269287
270288 const port = parseInt ( process . env . PORT ) ;
271289
272- serve ( {
290+ const server = serve ( {
273291 fetch : app . fetch ,
274292 port
275293 } ) ;
276294
295+ injectWebSocket ( server ) ;
296+
277297 console . log (
278298 `\nServer running. OpenAPI documentation available at http://localhost:${ port } /doc`
279299 ) ;
0 commit comments