|
| 1 | +# Backend (`server/`) |
| 2 | + |
| 3 | +Built with **Node.js + Express + WebSocket** |
| 4 | + |
| 5 | +## Technologies |
| 6 | + |
| 7 | +- **Node.js** - runtime |
| 8 | +- **Express** - HTTP server and routing |
| 9 | +- **ws** - WebSocket server for real-time broadcasting |
| 10 | +- **uuid** - generating unique message IDs |
| 11 | +- **cors** - allowing cross-origin requests from the frontend |
| 12 | + |
| 13 | +## Structure |
| 14 | + |
| 15 | +``` |
| 16 | +server/ |
| 17 | + index.js - server setup, middleware, WebSocket, routes |
| 18 | + data/ |
| 19 | + messages.js - shared in-memory messages array |
| 20 | + endPoints/ |
| 21 | + getMessage.js - handles GET /messages |
| 22 | + postMessage.js - handles POST /messages and broadcasts via WebSocket |
| 23 | +``` |
| 24 | + |
| 25 | +## Implementation |
| 26 | + |
| 27 | +`index.js` |
| 28 | + |
| 29 | +- Sets up Express with `cors` and `body-parser` middleware |
| 30 | +- Creates an HTTP server and attaches a WebSocket server to the same port |
| 31 | +- Logs when clients connect and disconnect via WebSocket |
| 32 | +- Mounts `GET /messages` and `POST /messages` routes |
| 33 | +- Passes the `wss` instance into `postMessage` so it can broadcast |
| 34 | + |
| 35 | +`data/messages.js` |
| 36 | + |
| 37 | +- Exports a shared in-memory array that both endpoints read from and write to |
| 38 | + |
| 39 | +`endPoints/getMessage.js` |
| 40 | + |
| 41 | +- Returns the full messages array as JSON |
| 42 | + |
| 43 | +`endPoints/postMessage.js` |
| 44 | + |
| 45 | +- Validates that `name` and `text` are present in the request body |
| 46 | +- Returns `400` if either is missing |
| 47 | +- Creates a new message with `uuid` for `id` and server-generated `timestamp` |
| 48 | +- Pushes the message to the shared array |
| 49 | +- Broadcasts the new message to all connected WebSocket clients with `readyState === 1` |
| 50 | +- Returns `201` with the created message |
| 51 | + |
| 52 | +## What I Learned |
| 53 | + |
| 54 | +Building this project showed how a single server can handle both REST and WebSocket on the same port, and how passing the WebSocket server instance into route handlers is the key to broadcasting messages to all connected clients after a POST request. |
0 commit comments