SessionScriptHelper
This file defines the SessionScriptHelper
class, which provides methods for managing user-defined session data within a script context. It interacts with the session data stored on a Bun socket, allowing scripts to set, get, delete, and query session values.
Features
- Session Storage: Store and retrieve arbitrary key-value pairs for the session.
- Type Safety: Supports generic typing for
get
operations. - Session Management: Methods to clear, delete, check, and enumerate session data.
Usage
typescript
const session = new SessionScriptHelper(socket);
session.set('username', 'alice');
const username = session.get<string>('username');
const allData = session.getAll();
session.delete('username');
session.clear();
const hasKey = session.has('username');
const keys = session.keys();
const values = session.values();
API
Constructor
typescript
constructor(
private socket: Socket<IScriptSocketData>,
)
- socket: The Bun socket instance containing session data.
Methods
set(key: string, value: any): void
Sets a value for the given key in the session.
get<T = string>(key: string): T | null
Retrieves the value for the given key, or null
if not set.
getAll(): Record<string, any>
Returns all user-defined session data as an object.
delete(key: string): void
Deletes the value for the given key from the session.
clear(): void
Clears all user-defined session data.
has(key: string): boolean
Checks if a value exists for the given key.
keys(): string[]
Returns an array of all keys in the session data.
values(): any[]
Returns an array of all values in the session data.
Notes
- Designed for use in script helpers or CLI tools that need to persist data across a session.
- All session data is stored in the
userDefined
property of the socket's data object.