Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 72 additions & 2 deletions routes/common.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
import { ErrorRequestHandler, RequestHandler } from "express";
import logger from "../utils/logger";

/**
* Middleware function that handles requests for routes that are not found.
* It checks if the response headers have already been sent; if so, it calls the next middleware.
* If the headers have not been sent, it logs an error message and responds with a 404 status code.
*
* @param {Request} req - The request object representing the HTTP request.
* @param {Response} res - The response object used to send a response to the client.
* @param {NextFunction} next - The next middleware function in the stack.
*
* @returns {void} This function does not return a value.
*
* @throws {Error} Throws an error if logging fails (if logger is not defined).
*
* @example
* // Usage in an Express application
* app.use(notFound);
*/
export const notFound: RequestHandler = (req, res, next) => {
if (res.headersSent) {
return next()
Expand All @@ -9,17 +26,70 @@ export const notFound: RequestHandler = (req, res, next) => {
res.status(404).json({ message: `No ${req.method} handler for ${req.path}` })
}

/**
* Middleware function for health check endpoint.
*
* This function responds with a status code of 200 and a message 'pong'.
* It is typically used to verify that the server is running and responsive.
*
* @param {Request} _ - The request object (not used in this function).
* @param {Response} res - The response object used to send the response.
* @param {NextFunction} next - The next middleware function in the stack.
*
* @returns {void} This function does not return a value.
*
* @example
* // Example usage in an Express application:
* app.get('/health', healthcheck);
*
* @throws {Error} If there is an issue with sending the response.
*/
export const healthcheck: RequestHandler = (_, res, next) => {
res.status(200).send('pong')
next()
}

/** Log response */
/**
* Middleware function that logs the HTTP response details.
*
* This function logs the HTTP method, request path, and response status code
* whenever a request is processed. It is intended to be used as a middleware
* in an Express.js application to help with monitoring and debugging.
*
* @param {Request} req - The HTTP request object.
* @param {Response} res - The HTTP response object.
* @param {NextFunction} next - The next middleware function in the stack.
*
* @returns {void} This function does not return a value.
*
* @example
* // Usage in an Express application
* app.use(responseLogger);
*
* @throws {Error} Throws an error if logging fails.
*/
export const responseLogger: RequestHandler = (req, res, next) => {
logger.info(`${req.method} ${req.path} ${res.statusCode}`)
}

/** Error Handler */
/**
* Middleware function to handle errors in the application.
* This function logs the error details and sends a JSON response
* with the error message to the client if headers have not been sent.
*
* @param {Error} err - The error object that was thrown.
* @param {Request} req - The request object representing the HTTP request.
* @param {Response} res - The response object used to send a response to the client.
* @param {NextFunction} next - The next middleware function in the stack.
*
* @returns {void} This function does not return a value.
*
* @throws {Error} Throws an error if logging fails (not handled in this function).
*
* @example
* // Example usage in an Express application
* app.use(errorHandler);
*/
export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
logger.error(`${req.method} ${req.path} 500 ${err.message}`)
if (!res.headersSent)
Expand Down
20 changes: 20 additions & 0 deletions routes/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,26 @@ import config, { wsConfig } from '../utils/config'
import generifyMessage from '../utils/generifyMessage'
import logger from '../utils/logger'

/**
* Establishes a WebSocket connection to the specified server and sets up event handling for connected sockets.
*
* This function initializes a WebSocket server using the provided server instance. It configures the server based on the application settings, including enabling admin instrumentation and handling socket events such as connection, disconnection, and custom events defined in the configuration.
*
* @param {Server} server - The server instance to which the WebSocket server will be attached.
* @throws {Error} Throws an error if the server is not valid or if there are issues initializing the WebSocket server.
*
* @returns {WebSocketServer} The initialized WebSocket server instance.
*
* @example
* import connectSocket from './path/to/connectSocket';
*
* const server = createServer();
* const io = connectSocket(server);
*
* io.on('connection', (socket) => {
* console.log('New client connected:', socket.id);
* });
*/
export default function connectSocket(server: Server) {
const io = new WebSocketServer(server, wsConfig)

Expand Down
26 changes: 26 additions & 0 deletions utils/generifyMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,32 @@ import { SocketMessage } from '../types/message'

const STRING_OR_ARRAY_FIELDS: (keyof SocketMessage)[] = [ 'broadcastTo', 'join', 'leave' ]

/**
* Transforms specific fields of a SocketMessage into an array format if they are strings.
*
* This function takes an incoming SocketMessage object and checks certain fields.
* If the field is a string and is not 'message' or 'to', it converts that field's value
* into an array containing that string.
*
* @param {SocketMessage} incomingMessage - The SocketMessage object to be transformed.
* @returns {SocketMessage} The transformed SocketMessage object with specified fields as arrays.
*
* @example
* const message = {
* message: "Hello",
* to: "User",
* from: "Sender"
* };
* const result = generifyMessage(message);
* // result will be:
* // {
* // message: "Hello",
* // to: "User",
* // from: ["Sender"]
* // }
*
* @throws {TypeError} Throws an error if incomingMessage is not of type SocketMessage.
*/
export default function generifyMessage(incomingMessage: SocketMessage) {
const parsedMessage: SocketMessage = incomingMessage

Expand Down