@ajayos/server
Version:
A lightweight Express-based HTTP/HTTPS server wrapper with built-in middleware, lifecycle hooks, logging, and utility helpers.
309 lines (295 loc) • 11.8 kB
TypeScript
import { Application, RequestHandler } from 'express';
import * as express from 'express';
export { express };
export { Application, Router } from 'express';
import * as http from 'http';
import { ServerOptions } from 'http';
import * as https from 'https';
import { CorsOptions } from 'cors';
import { ServeStaticOptions } from 'serve-static';
import helmetObject from 'helmet';
import { TimeoutOptions } from 'connect-timeout';
import { Options } from 'express-rate-limit';
import { OptionsJson } from 'body-parser';
import { CompressionOptions } from 'compression';
import { CookieParseOptions } from 'cookie-parser';
/**
* Plugin interface for extending server functionality.
*/
interface ServerPlugin {
/** Name of the plugin */
name: string;
/** Setup function to initialize the plugin with the server application */
setup(app: Application): void;
}
/**
* HTTPS options for secure server
*/
interface HTTPSOptions {
/** Private key for HTTPS */
key: string | Buffer;
/** Certificate for HTTPS */
cert: string | Buffer;
}
/**
* Configuration options for the Server instance.
*/
interface ServerConfig {
/** Optional port number. Defaults to process.env.PORT or 8123. */
port?: number;
/** List of plugins to register on initialization. */
plugins?: any[];
/** Secure server options. If provided, the server will run over HTTPS. */
https?: ServerOptions | undefined;
/** Callback to run when the server starts. */
onServerStart?: ServerCallback;
/** Callback to handle server errors. */
onServerError?: (error: NodeJS.ErrnoException) => void;
/** cors middleware configuration */
cors?: boolean | any;
/** json middleware configuration */
json?: boolean;
/** urlencoded middleware configuration */
urlencoded?: boolean;
/** morgan middleware configuration */
morgan?: boolean | string;
/** helmet middleware configuration */
helmet?: boolean | object;
/** compression middleware configuration */
compression?: boolean | object;
/** rateLimit middleware configuration */
rateLimit?: boolean | object;
/** bodyParser middleware configuration */
bodyParser?: boolean | object;
/** cookieParser middleware configuration */
cookieParser?: boolean | {
secret?: string | string[];
options?: any;
};
/** static middleware configuration */
static?: string;
/** HTTPS options for secure server */
options?: HTTPSOptions | false;
}
/** Type alias for Express middleware */
type Middleware = RequestHandler;
/** Callback type for server events */
type ServerCallback = () => void;
/** Type alias for built-in plugin factory functions */
type BuiltinPluginFactory = (options?: any) => ServerPlugin;
/** Type for JSON error handler configuration */
type JsonErrorHandler = object | ((error: SyntaxError, req: any, res: any) => void);
/**
* Options for the router plugin.
* - prefix: Optional string to prefix all routes.
* - extensions: Array of file extensions to consider as route files.
* - verbose: Boolean flag to enable verbose logging.
*/
interface RouterPluginOptions {
prefix?: string;
extensions?: string[];
verbose?: boolean;
}
/**
* A robust wrapper class for an Express application.
* * This class simplifies the initialization of an Express server by handling:
* - HTTP vs HTTPS configuration
* - Plugin management
* - Argument normalization for flexible constructors
* - Built-in middleware application
*/
declare class SERVER {
/** The underlying Express application instance. */
app: Application;
/** The Node.js HTTP or HTTPS server instance. */
server: http.Server | https.Server;
/** The port the server is listening on. */
port: number;
/** Callback executed when the server starts listening. */
onServerStart: ServerCallback;
/** Callback executed when a server error occurs. */
onServerError: (error: any) => void;
/** Manager instance for handling server plugins. */
private plugins;
/** Configuration object for the server. */
private config;
constructor();
constructor(port: number);
constructor(port: number, cb: ServerCallback);
constructor(port: number, config: ServerConfig);
constructor(port: number, config: ServerConfig, cb: ServerCallback);
constructor(config: ServerConfig);
constructor(config: ServerConfig, cb: ServerCallback);
/**
* Starts the server.
* * 1. Applies built-in middleware (CORS, BodyParser, etc.).
* 2. Applies registered plugins.
* 3. Creates the HTTP or HTTPS server.
* 4. Listens on the specified port.
* * @throws {Error} If HTTPS is enabled but SSL options are missing.
*/
start(callback?: Function): void;
/**
* Closes the server and exits the process.
*/
close(): void;
/**
* Registers a new plugin to the server.
* Plugins are applied to the Express app when `start()` is called.
* * @param plugin - The plugin instance or function to register.
*/
usePlugin(plugin: ServerPlugin): void;
/**
* Applies built-in middleware based on the server configuration.
* Supported built-ins include CORS, Helmet, BodyParser, CookieParser, and Static file serving.
*/
applyBuiltins(): void;
/**
* Retrieves a list of active IPv4 network interfaces (excluding internal localhost).
* Useful for displaying access URLs in the console (e.g., http://192.168.1.5:8080).
* * @returns A record where keys are interface names and values are arrays of IP addresses.
*/
getActiveNetworkInterfaces(): Record<string, string[]>;
/**
* Mounts specified middleware function(s) at the specified path.
* If the path is not specified, it defaults to "/".
* * @param handlers - Request handlers (middleware).
*/
use(...handlers: RequestHandler[]): void;
/**
* Routes HTTP GET requests to the specified path with the specified callback functions.
* * @param path - The route path.
* @param handlers - Callback functions to handle the request.
*/
get(path: string, ...handlers: RequestHandler[]): void;
/**
* Routes HTTP POST requests to the specified path with the specified callback functions.
* * @param path - The route path.
* @param handlers - Callback functions to handle the request.
*/
post(path: string, ...handlers: RequestHandler[]): void;
/**
* Routes HTTP PUT requests to the specified path with the specified callback functions.
* * @param path - The route path.
* @param handlers - Callback functions to handle the request.
*/
put(path: string, ...handlers: RequestHandler[]): void;
/**
* Routes HTTP DELETE requests to the specified path with the specified callback functions.
* * @param path - The route path.
* @param handlers - Callback functions to handle the request.
*/
delete(path: string, ...handlers: RequestHandler[]): void;
/**
* Routes HTTP PATCH requests to the specified path with the specified callback functions.
* * @param path - The route path.
* @param handlers - Callback functions to handle the request.
*/
patch(path: string, ...handlers: RequestHandler[]): void;
/**
* Routes HTTP requests (all methods) to the specified path with the specified callback functions.
* * @param path - The route path.
* @param handlers - Callback functions to handle the request.
*/
all(path: string, ...handlers: RequestHandler[]): void;
/**
* Registers an event listener on the underlying Express application.
* * @param event - The event name.
* @param listener - The callback function to execute when the event is emitted.
*/
on(event: string, listener: (...args: any[]) => void): void;
/**
* Removes an event listener from the underlying Express application.
* @param event - The event name.
* @param listener - The callback function to remove.
*/
off(event: string, listener: (...args: any[]) => void): void;
/**
* Registers a one-time event listener on the underlying Express application.
* @param event - The event name.
* @param listener - The callback function to execute when the event is emitted.
*/
once(event: string, listener: (...args: any[]) => void): void;
/**
* Registers an event listener on the underlying Express application.
* @param event - The event name.
* @param listener - The callback function to execute when the event is emitted.
*/
onApp(event: string, listener: (...args: any[]) => void): void;
/**
* Removes an event listener from the underlying Express application.
* @param event - The event name.
* @param listener - The callback function to remove.
*/
offApp(event: string, listener: (...args: any[]) => void): void;
/**
* Registers a one-time event listener on the underlying Express application.
* @param event - The event name.
* @param listener - The callback function to execute when the event is emitted.
*/
onceApp(event: string, listener: (...args: any[]) => void): void;
}
/**
* CORS middleware plugin
* @param options - CORS configuration options
* @returns ServerPlugin
*/
declare const cors: (options?: CorsOptions | undefined) => ServerPlugin;
/**
* Static file serving middleware plugin
* @param root - Root directory to serve static files from
* @param options - Static file serving options
* @returns ServerPlugin
*/
declare const staticPlugin: (root: string, options?: ServeStaticOptions) => ServerPlugin;
/**
* Morgan middleware plugin for request logging
* @param format - Morgan log format (default: 'dev')
* @returns ServerPlugin
*/
declare const morgan: (format?: string) => ServerPlugin;
/**
* Helmet middleware plugin
* @param options - Helmet configuration options
* @returns ServerPlugin
*/
declare const helmet: (options?: Parameters<typeof helmetObject>[0]) => ServerPlugin;
/**
* Timeout middleware plugin
* @param time - Timeout duration (e.g., '5s', '2m')
* @param options - Timeout configuration options
* @returns ServerPlugin
*/
declare const timeout: (time: string | number, options?: TimeoutOptions | undefined) => ServerPlugin;
/**
* JSON Error middleware plugin
* @param handler - Custom error handler or error response object
* @returns ServerPlugin
*/
declare const jsonError: (handler?: JsonErrorHandler) => ServerPlugin;
/**
* Rate Limiting middleware plugin
* @param options - Rate limiting configuration options
* @returns ServerPlugin
*/
declare const rateLimit: (options?: Options) => ServerPlugin;
/**
* Body Parser middleware plugin
* @param options - Body Parser JSON configuration options
* @returns ServerPlugin
*/
declare const bodyParser: (options?: OptionsJson | undefined) => ServerPlugin;
/**
* Compression middleware plugin
* @param options - Compression configuration options
* @returns ServerPlugin
*/
declare const compression: (options?: CompressionOptions) => ServerPlugin;
/**
* Cookie Parser middleware plugin
* @param secret - Optional secret for signed cookies
* @param options - Cookie parser options
* @returns ServerPlugin
*/
declare const cookieParser: (secret?: string | string[] | undefined, options?: CookieParseOptions | undefined) => ServerPlugin;
export { type BuiltinPluginFactory, type HTTPSOptions, type JsonErrorHandler, type Middleware, type RouterPluginOptions, SERVER, type ServerCallback, type ServerConfig, type ServerPlugin, bodyParser, compression, cookieParser, cors, SERVER as default, helmet, jsonError, morgan, rateLimit, staticPlugin as static, timeout };