File tree Expand file tree Collapse file tree 2 files changed +44
-2
lines changed
Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Original file line number Diff line number Diff line change @@ -67,6 +67,32 @@ wss.on('connection', async (ws) => {
6767 if ( message . header === 'LINKS' && db ) {
6868 const linksCollection = db . collection ( 'links' ) ;
6969
70+ // Handle syncing websocket state with database
71+ if ( message . type === 'sync_links' ) {
72+ if ( message . links && message . links . length > 0 ) {
73+ // If websocket has links, replace database content
74+ try {
75+ await linksCollection . deleteMany ( { } ) ;
76+ await linksCollection . insertMany ( message . links ) ;
77+ console . log ( 'Database synchronized with WebSocket state' ) ;
78+ } catch ( err ) {
79+ console . error ( 'Error syncing database:' , err ) ;
80+ }
81+ } else {
82+ // If no links in websocket, try to get from database
83+ const dbLinks = await linksCollection . find ( { } ) . sort ( { createdAt : - 1 } ) . toArray ( ) ;
84+ if ( dbLinks . length > 0 ) {
85+ ws . send ( JSON . stringify ( {
86+ header : 'LINKS' ,
87+ type : 'links_list' ,
88+ links : dbLinks
89+ } ) ) ;
90+ console . log ( 'Sent database links to client' ) ;
91+ }
92+ }
93+ return ;
94+ }
95+
7096 if ( message . type === 'delete_link' ) {
7197 try {
7298 // Delete the link from MongoDB
Original file line number Diff line number Diff line change @@ -45,8 +45,12 @@ function LinksGrid() {
4545 setStatus ( 'Connected' ) ;
4646 console . log ( 'WebSocket connected' ) ;
4747
48- // Request existing links
49- newWs . send ( JSON . stringify ( { header : 'LINKS' , type : 'request_links' } ) ) ;
48+ // Send sync request instead of just requesting links
49+ newWs . send ( JSON . stringify ( {
50+ header : 'LINKS' ,
51+ type : 'sync_links' ,
52+ links : [ ] // Empty array to trigger database check
53+ } ) ) ;
5054 } ;
5155
5256 newWs . onmessage = ( event ) => {
@@ -121,6 +125,18 @@ function LinksGrid() {
121125 } , [ ] ) ;
122126
123127 // Effect for WebSocket connection management
128+ // Effect for database synchronization
129+ useEffect ( ( ) => {
130+ if ( ws && ws . readyState === WebSocket . OPEN ) {
131+ // Send sync request
132+ ws . send ( JSON . stringify ( {
133+ header : 'LINKS' ,
134+ type : 'sync_links' ,
135+ links : links
136+ } ) ) ;
137+ }
138+ } , [ ws , links ] ) ;
139+
124140 useEffect ( ( ) => {
125141 console . log ( 'Initializing WebSocket connection...' ) ;
126142 const cleanup = connect ( ) ;
You can’t perform that action at this time.
0 commit comments