BaseThread
This file defines the BaseThread
class, which serves as the base class for all threads in the @sodacore/core
library. It handles loading user configuration via the @Configure
decorator, provides logging utilities, argument parsing, and inter-process communication (IPC) with the parent process.
Features
- User Configuration: Loads user config metadata for the thread.
- Logging: Provides methods to log messages (
info
,warn
,error
) back to the parent process. - Argument Parsing: Parses and retrieves thread arguments from
process.argv
. - IPC Dispatch: Allows sending commands and context to the parent process and awaiting responses.
Usage
typescript
import BaseThread from './base/thread';
class MyThread extends BaseThread {
async runTask() {
this.info('Running task in thread');
const config = this.getConfig();
const arg = this.getArgv('myArg');
const result = await this.dispatch('controller:method', { data: 'value' });
}
}
API
Properties
- userConfig: Private. Stores user configuration loaded from metadata.
- module: Protected. Reference to the module instance (can be set by subclasses).
- methods: Protected. Map of method names to async handlers for thread messages.
Constructor
typescript
constructor(private wrapper: ThreadWrapper)
- wrapper: The thread wrapper instance. Triggers loading of user config.
Methods
protected getConfig<T = unknown>(key?: string): T
Returns the user config object or a specific key from the config.
public log(type: ILoggerType, message: string): void
Logs a message of the given type back to the parent process.
public info(message: string): void
Shorthand for logging an info message.
public warn(message: string): void
Shorthand for logging a warning message.
public error(message: string): void
Shorthand for logging an error message.
public getArgv<T = Record<string, any>>(arg?: string): T
Parses and returns all thread arguments or a specific argument from process.argv
.
public async dispatch<T = any>(command: string, context?: Record<string, any>, timeout = 5000): Promise<T>
Sends a command and context to the parent process and waits for a response, with an optional timeout (default: 5000ms).
Notes
- Extend this class for all thread implementations to ensure consistent configuration, logging, and IPC.
- Uses dependency injection utilities and metadata helpers from
@sodacore/di
. - The
dispatch
method uses a unique ID and the thread wrapper's IPC callback system to handle responses.