Network -- API Reference
Architecture
BaseHelper
├── BaseNetworkRequest<T extends TFetcherVariant>
│ ├── AxiosNetworkRequest (T = 'axios')
│ └── NodeFetchNetworkRequest (T = 'node-fetch')
│
├── BaseNetworkTcpServer<ServerOpts, ServerType, ClientType>
│ ├── NetworkTcpServer (net.Server, net.Socket)
│ └── NetworkTlsTcpServer (tls.Server, tls.TLSSocket)
│
├── BaseNetworkTcpClient<ClientOpts, ClientType>
│ ├── NetworkTcpClient (net.TcpSocketConnectOpts, net.Socket)
│ └── NetworkTlsTcpClient (tls.ConnectionOptions, tls.TLSSocket)
│
└── NetworkUdpClient
AbstractNetworkFetchableHelper<V, RQ, RS> (implements IFetchable)
├── AxiosFetcher (V = 'axios')
└── NodeFetcher (V = 'node-fetch')All classes that extend BaseHelper inherit scoped logging via this.logger.
HTTP Request API
BaseNetworkRequest
class BaseNetworkRequest<T extends TFetcherVariant> extends BaseHelperBase class for HTTP request helpers. Holds a base URL and delegates to an IFetchable fetcher.
Constructor
constructor(opts: {
name: string;
baseUrl?: string;
fetcher: IFetchable<T, IRequestOptions, TFetcherResponse<T>>;
})| Parameter | Type | Description |
|---|---|---|
name | string | Helper name, used as both scope and identifier for logging |
baseUrl | string | Base URL prepended to request paths. Defaults to '' |
fetcher | IFetchable | The underlying HTTP fetcher implementation |
Methods
getRequestUrl(opts)
Builds a full URL by combining a base URL with path segments. Throws if no base URL is available.
getRequestUrl(opts: {
baseUrl?: string;
paths: Array<string>;
}): string| Parameter | Type | Description |
|---|---|---|
baseUrl | string | Overrides the instance's base URL. Falls back to this.baseUrl |
paths | string[] | Path segments to append. Each is prefixed with / if missing |
Throws: Error with message '[getRequestUrl] Invalid configuration for third party request base url!' when both opts.baseUrl and this.baseUrl are empty.
Example:
client.getRequestUrl({ paths: ['v1', 'users', '123'] });
// => 'https://api.example.com/v1/users/123'
client.getRequestUrl({ baseUrl: 'https://other.api.com', paths: ['health'] });
// => 'https://other.api.com/health'getRequestPath(opts)
Joins path segments, ensuring each starts with /.
getRequestPath(opts: { paths: Array<string> }): stringExample:
client.getRequestPath({ paths: ['v1', 'users'] });
// => '/v1/users'getNetworkService()
Returns the underlying IFetchable fetcher instance.
getNetworkService(): IFetchable<T, IRequestOptions, TFetcherResponse<T>>getWorker()
Returns the raw HTTP client from the fetcher (AxiosInstance for Axios, typeof fetch for Node Fetch).
getWorker(): TFetcherWorker<T>IFetchable Interface
interface IFetchable<
V extends TFetcherVariant,
RQ extends IRequestOptions,
RS extends TFetcherResponse<V>,
> {
send(opts: RQ, logger?: any): Promise<RS>;
get(opts: RQ, logger?: any): Promise<RS>;
post(opts: RQ, logger?: any): Promise<RS>;
put(opts: RQ, logger?: any): Promise<RS>;
patch(opts: RQ, logger?: any): Promise<RS>;
delete(opts: RQ, logger?: any): Promise<RS>;
getWorker(): TFetcherWorker<V>;
}All HTTP method shortcuts (get, post, put, patch, delete) delegate to send() with the method field set accordingly.
IRequestOptions
interface IRequestOptions {
url: string;
params?: Record<string | symbol, any>;
method?: string;
timeout?: number;
[extra: symbol | string]: any;
}AbstractNetworkFetchableHelper
abstract class AbstractNetworkFetchableHelper<
V extends TFetcherVariant,
RQ extends IRequestOptions,
RS extends TFetcherResponse<V>,
> implements IFetchable<V, RQ, RS>Abstract base for fetcher implementations. Provides convenience HTTP method wrappers and protocol detection.
Constructor
constructor(opts: { name: string; variant: V })Methods
abstract send(opts, logger?)
Subclasses must implement the actual request dispatch.
abstract send(opts: RQ, logger?: any): Promise<RS>;get(opts, logger?)
get(opts: RQ, logger?: any): Promise<RS>Calls send() with method: 'get'.
post(opts, logger?)
post(opts: RQ, logger?: any): Promise<RS>Calls send() with method: 'post'.
put(opts, logger?)
put(opts: RQ, logger?: any): Promise<RS>Calls send() with method: 'put'.
patch(opts, logger?)
patch(opts: RQ, logger?: any): Promise<RS>Calls send() with method: 'patch'.
delete(opts, logger?)
delete(opts: RQ, logger?: any): Promise<RS>Calls send() with method: 'delete'.
getProtocol(url)
Returns 'http' or 'https' based on the URL prefix.
getProtocol(url: string): 'http' | 'https'getWorker()
Returns the underlying HTTP client instance.
getWorker(): TFetcherWorker<V>AxiosFetcher
class AxiosFetcher extends AbstractNetworkFetchableHelper<
'axios',
IAxiosRequestOptions,
AxiosResponse['data']
>Axios-based fetcher implementation. Creates an axios instance with the provided default configuration.
Constructor
constructor(opts: {
name: string;
defaultConfigs: AxiosRequestConfig;
logger?: any;
})IAxiosRequestOptions
interface IAxiosRequestOptions extends AxiosRequestConfig, IRequestOptions {
url: string;
method?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options';
params?: AnyObject;
body?: AnyObject; // Mapped to Axios `data`
headers?: AnyObject;
}NOTE
The body field is mapped to Axios's data field internally. Query parameters are serialized using node:querystring. For HTTPS URLs, an https.Agent is automatically created with rejectUnauthorized defaulting to false.
Methods
send(opts, logger?)
override send<T = any>(opts: IAxiosRequestOptions, logger?: any): Promise<AxiosResponse<T>>Dispatches the request via the internal axios instance. For HTTPS URLs, automatically configures an https.Agent.
AxiosNetworkRequest
class AxiosNetworkRequest extends BaseNetworkRequest<'axios'>Pre-configured HTTP client using Axios.
Constructor
constructor(opts: IAxiosNetworkRequestOptions)interface IAxiosNetworkRequestOptions {
name: string;
networkOptions: Omit<AxiosRequestConfig, 'baseURL'> & {
baseUrl?: string;
};
}Default configuration applied:
| Setting | Default |
|---|---|
headers['content-type'] | 'application/json; charset=utf-8' |
withCredentials | true |
validateStatus | (status) => status < 500 |
timeout | 60000 (1 minute) |
User-provided values in networkOptions override all defaults.
NodeFetcher
class NodeFetcher extends AbstractNetworkFetchableHelper<
'node-fetch',
INodeFetchRequestOptions,
Awaited<ReturnType<typeof fetch>>
>Native fetch based fetcher implementation.
Constructor
constructor(opts: {
name: string;
defaultConfigs: RequestInit;
logger?: any;
})INodeFetchRequestOptions
interface INodeFetchRequestOptions extends RequestInit, IRequestOptions {
url: string;
params?: Record<string | symbol, any>;
}Methods
send(opts, logger?)
override async send(opts: INodeFetchRequestOptions, logger?: any): Promise<Response>Dispatches the request using the native fetch API. If timeout is provided, creates an AbortController that aborts the request after the specified duration in milliseconds. Query params are serialized using node:querystring and appended to the URL.
NodeFetchNetworkRequest
class NodeFetchNetworkRequest extends BaseNetworkRequest<'node-fetch'>Pre-configured HTTP client using native fetch.
Constructor
constructor(opts: INodeFetchNetworkRequestOptions)interface INodeFetchNetworkRequestOptions {
name: string;
networkOptions: RequestInit & {
baseUrl?: string;
};
}Default configuration applied:
| Setting | Default |
|---|---|
headers['content-type'] | 'application/json; charset=utf-8' |
If headers is a Headers instance, it is converted to a plain object via Object.fromEntries() before merging.
TCP Socket API
BaseNetworkTcpServer
class BaseNetworkTcpServer<
SocketServerOptions extends ServerOpts = ServerOpts,
SocketServerType extends SocketServer = SocketServer,
SocketClientType extends SocketClient = SocketClient,
> extends BaseHelperAbstract TCP server with client tracking, authentication flow, and event delegation.
Constructor
constructor(opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>)Throws: Error with message 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions' when authenticateOptions.required is true and duration is missing or negative.
The constructor automatically calls configure(), which creates the server and starts listening.
Protected Properties
| Property | Type | Description |
|---|---|---|
serverOptions | Partial<SocketServerOptions> | Server creation options |
listenOptions | Partial<ListenOptions> | Listen configuration |
authenticateOptions | { required: boolean; duration?: number } | Auth settings |
clients | Record<string, ITcpSocketClient<SocketClientType>> | Connected client registry |
server | SocketServerType | The underlying server instance |
extraEvents | Record<string, (opts) => void> | Additional per-client socket events |
Methods
configure()
Creates the server using createServerFn and starts listening. Called automatically by the constructor.
configure(): voidonNewConnection(opts)
Handles a new client connection. Assigns a unique ID, registers data, error, close, and extra events, tracks the client, and starts the authentication timer if required.
onNewConnection(opts: { socket: SocketClientType }): voidgetClients()
Returns all connected clients as a record keyed by client ID.
getClients(): Record<string, ITcpSocketClient<SocketClientType>>getClient(opts)
Returns a specific connected client by ID, or undefined if not found.
getClient(opts: { id: string }): ITcpSocketClient<SocketClientType> | undefinedgetServer()
Returns the underlying server instance.
getServer(): SocketServerTypedoAuthenticate(opts)
Transitions a client's authentication state. Sets authenticatedAt timestamp when state becomes 'authenticated', clears it otherwise.
doAuthenticate(opts: {
id: string;
state: 'unauthorized' | 'authenticating' | 'authenticated';
}): voidemit(opts)
Writes data to a specific client's socket. Silently returns (with a log warning) if the client is not found, the socket is not writable, or the payload is empty.
emit(opts: { clientId: string; payload: Buffer | string }): voidITcpSocketClient
interface ITcpSocketClient<SocketClientType> {
id: string;
socket: SocketClientType;
state: 'unauthorized' | 'authenticating' | 'authenticated';
subscriptions: Set<string>;
storage: {
connectedAt: dayjs.Dayjs;
authenticatedAt: dayjs.Dayjs | null;
[additionField: symbol | string]: any;
};
}NetworkTcpServer
class NetworkTcpServer extends BaseNetworkTcpServer<ServerOpts, Server, Socket>Plain TCP server using net.createServer.
Constructor
constructor(opts: Omit<ITcpSocketServerOptions, 'createServerFn'>)The createServerFn is pre-set to net.createServer. The scope is set to 'NetworkTcpServer'.
Static Methods
newInstance(opts)
Factory method that creates a new NetworkTcpServer.
static newInstance(
opts: Omit<ITcpSocketServerOptions, 'createServerFn'>
): NetworkTcpServerNetworkTlsTcpServer
class NetworkTlsTcpServer extends BaseNetworkTcpServer<TlsOptions, tls.Server, TLSSocket>TLS-encrypted TCP server using tls.createServer.
Constructor
constructor(opts: Omit<ITcpSocketServerOptions, 'createServerFn'>)The createServerFn is pre-set to tls.createServer. The scope is set to 'NetworkTlsTcpServer'. Pass TLS certificates and keys in serverOptions (type TlsOptions from node:tls).
Static Methods
newInstance(opts)
static newInstance(
opts: Omit<ITcpSocketServerOptions, 'createServerFn'>
): NetworkTlsTcpServerBaseNetworkTcpClient
class BaseNetworkTcpClient<
SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,
SocketClientType extends PlainSocketClient | TlsSocketClient,
> extends BaseHelperAbstract TCP client with auto-reconnect, encoding support, and lifecycle hooks.
Constructor
constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>)Protected Properties
| Property | Type | Description |
|---|---|---|
client | SocketClientType | null | The underlying socket, or null when disconnected |
options | SocketClientOptions | Connection options |
reconnect | boolean | Whether auto-reconnect is enabled (default: false) |
retry | { maxReconnect: number; currentReconnect: number } | Reconnect state. maxReconnect defaults to 5 |
encoding | BufferEncoding | undefined | Socket encoding |
Methods
connect(opts)
Establishes the connection. If already connected, logs and returns. Creates the socket using createClientFn, registers data, close, and error events, and applies encoding if set.
connect(opts: { resetReconnectCounter: boolean }): void| Parameter | Type | Description |
|---|---|---|
resetReconnectCounter | boolean | If true, resets retry.currentReconnect to 0 |
disconnect()
Destroys the socket, clears the reconnect timeout, and sets client to null.
disconnect(): voidforceReconnect()
Calls disconnect() then connect({ resetReconnectCounter: true }).
forceReconnect(): voidisConnected()
Returns a truthy value if the client exists and its readyState is not 'closed'.
isConnected(): SocketClientType | null | undefinedemit(opts)
Writes data to the server. Silently returns (with a log) if the client is not initialized or the payload is empty.
emit(opts: { payload: Buffer | string }): voidgetClient()
Returns the underlying socket instance, or null/undefined if not connected.
getClient(): SocketClientType | null | undefinedhandleConnected()
Default connection handler. Logs the connection and resets the reconnect counter.
handleConnected(): voidhandleData(_opts)
Default data handler. No-op.
handleData(_opts: { identifier: string; message: string | Buffer }): voidhandleClosed()
Default close handler. Logs the closure.
handleClosed(): voidhandleError(error)
Default error handler. Logs the error. If reconnect is enabled and the retry limit has not been reached, schedules a reconnect after 5 seconds.
handleError(error: any): voidNetworkTcpClient
class NetworkTcpClient extends BaseNetworkTcpClient<TcpSocketConnectOpts, Socket>Plain TCP client using net.connect.
Constructor
constructor(
opts: Omit<INetworkTcpClientProps<TcpSocketConnectOpts, Socket>, 'createClientFn'>
)The createClientFn is pre-set to net.connect. The scope is set to 'NetworkTcpClient'.
Static Methods
newInstance(opts)
static newInstance(
opts: Omit<INetworkTcpClientProps<TcpSocketConnectOpts, Socket>, 'createClientFn'>
): NetworkTcpClientNetworkTlsTcpClient
class NetworkTlsTcpClient extends BaseNetworkTcpClient<ConnectionOptions, TLSSocket>TLS-encrypted TCP client using tls.connect.
Constructor
constructor(
opts: Omit<INetworkTcpClientProps<ConnectionOptions, TLSSocket>, 'createClientFn'>
)The createClientFn is pre-set to tls.connect. The scope is set to 'NetworkTlsTcpClient'. Pass TLS certificates and keys in options (type ConnectionOptions from node:tls).
Static Methods
newInstance(opts)
static newInstance(
opts: Omit<INetworkTcpClientProps<ConnectionOptions, TLSSocket>, 'createClientFn'>
): NetworkTlsTcpClientUDP Socket API
NetworkUdpClient
class NetworkUdpClient extends BaseHelperUDP datagram client with multicast support, using node:dgram internally (UDP4).
Constructor
constructor(opts: INetworkUdpClientProps)interface INetworkUdpClientProps {
identifier: string;
host?: string;
port: number;
reuseAddr?: boolean;
multicastAddress?: {
groups?: Array<string>;
interface?: string;
};
onConnected?: (opts: { identifier: string; host?: string; port: number }) => void;
onData?: (opts: {
identifier: string;
message: string | Buffer;
remoteInfo: dgram.RemoteInfo;
}) => void;
onClosed?: (opts: { identifier: string; host?: string; port: number }) => void;
onError?: (opts: { identifier: string; host?: string; port: number; error: Error }) => void;
onBind?: (opts: {
identifier: string;
socket: dgram.Socket;
host?: string;
port: number;
reuseAddr?: boolean;
multicastAddress?: { groups?: Array<string>; interface?: string };
}) => ValueOrPromise<void>;
}Static Methods
newInstance(opts)
Factory method that creates a new NetworkUdpClient.
static newInstance(opts: INetworkUdpClientProps): NetworkUdpClientMethods
connect()
Creates a dgram.Socket (type 'udp4'), registers close, error, listening, and message events, then binds to the configured port and host. The onBind callback is invoked after binding completes -- use it to join multicast groups.
connect(): voidIf the client is already initialized, logs a message and returns. If port is not set, logs a message and returns.
disconnect()
Closes the underlying dgram.Socket and sets the client to null.
disconnect(): voidisConnected()
Returns the underlying socket if connected, or null/undefined if not.
isConnected(): dgram.Socket | null | undefinedgetClient()
Returns the underlying dgram.Socket instance, or null/undefined if not connected.
getClient(): dgram.Socket | null | undefinedhandleConnected()
Default connection handler. Logs the bind success with host, port, and multicast address.
handleConnected(): voidhandleData(opts)
Default data handler. Logs the received message and remote info.
handleData(opts: {
identifier: string;
message: string | Buffer;
remoteInfo: dgram.RemoteInfo;
}): voidhandleClosed()
Default close handler. Logs the closure with host and port.
handleClosed(): voidhandleError(opts)
Default error handler. Logs the error with host and port.
handleError(opts: { identifier: string; error: Error }): voidTypes Reference
TFetcherVariant
type TFetcherVariant = 'node-fetch' | 'axios';TFetcherResponse
type TFetcherResponse<T extends TFetcherVariant> =
T extends 'node-fetch' ? Response : AxiosResponse;TFetcherWorker
type TFetcherWorker<T extends TFetcherVariant> =
T extends 'axios' ? AxiosInstance : typeof fetch;ITcpSocketServerOptions
interface ITcpSocketServerOptions<
SocketServerOptions extends ServerOpts = ServerOpts,
SocketServerType extends SocketServer = SocketServer,
SocketClientType extends SocketClient = SocketClient,
> {
scope?: string;
identifier: string;
serverOptions: Partial<SocketServerOptions>;
listenOptions: Partial<ListenOptions>;
authenticateOptions: { required: boolean; duration?: number };
extraEvents?: Record<
string,
(opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>
>;
createServerFn: (
options: Partial<SocketServerOptions>,
connectionListener: (socket: SocketClientType) => void,
) => SocketServerType;
onServerReady?: (opts: { server: SocketServerType }) => void;
onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;
onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;
onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;
onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;
}INetworkTcpClientProps
interface INetworkTcpClientProps<
SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,
SocketClientType extends PlainSocketClient | TlsSocketClient,
> {
identifier: string;
scope?: string;
options: SocketClientOptions;
reconnect?: boolean;
maxRetry?: number;
encoding?: BufferEncoding;
createClientFn: (
options: SocketClientOptions,
connectionListener?: () => void,
) => SocketClientType;
onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;
onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;
onClosed?: (opts: { client: SocketClientType }) => void;
onError?: (error: any) => void;
}INetworkUdpClientProps
interface INetworkUdpClientProps {
identifier: string;
host?: string;
port: number;
reuseAddr?: boolean;
multicastAddress?: {
groups?: Array<string>;
interface?: string;
};
onConnected?: (opts: { identifier: string; host?: string; port: number }) => void;
onData?: (opts: {
identifier: string;
message: string | Buffer;
remoteInfo: dgram.RemoteInfo;
}) => void;
onClosed?: (opts: { identifier: string; host?: string; port: number }) => void;
onError?: (opts: { identifier: string; host?: string; port: number; error: Error }) => void;
onBind?: (opts: {
identifier: string;
socket: dgram.Socket;
host?: string;
port: number;
reuseAddr?: boolean;
multicastAddress?: { groups?: Array<string>; interface?: string };
}) => ValueOrPromise<void>;
}See Also
- Setup & Usage -- Getting started and examples