Generic interceptor for processing items with middleware pattern
const interceptor = new Interceptor<string>();const id = interceptor.use((str) => str.toUpperCase());const result = await interceptor.execute('hello'); // "HELLO"console.log(result);interceptor.reject(id); // Remove the handler Copy
const interceptor = new Interceptor<string>();const id = interceptor.use((str) => str.toUpperCase());const result = await interceptor.execute('hello'); // "HELLO"console.log(result);interceptor.reject(id); // Remove the handler
The type of item being processed
Get the number of registered handlers
Number of handlers in the chain
console.log(`Interceptor has ${interceptor.size} handlers`); Copy
console.log(`Interceptor has ${interceptor.size} handlers`);
Check if the interceptor has any handlers
True if no handlers are registered, false otherwise
if (interceptor.isEmpty) { console.log('No handlers registered');} Copy
if (interceptor.isEmpty) { console.log('No handlers registered');}
Register a new interceptor handler
Function to process the item
Unique ID for the registered handler
When handler is not a function
const id = interceptor.use((item) => { console.log('Processing:', item); return item;}); Copy
const id = interceptor.use((item) => { console.log('Processing:', item); return item;});
Execute all registered handlers in sequence
Item to process through the handler chain
Promise resolving to the processed item
When any handler fails
try { const result = await interceptor.execute(originalItem); console.log('Processed:', result);} catch (error) { console.error('Handler failed:', error.message);} Copy
try { const result = await interceptor.execute(originalItem); console.log('Processed:', result);} catch (error) { console.error('Handler failed:', error.message);}
Clear all registered handlers
interceptor.clear();console.log(interceptor.isEmpty); // true Copy
interceptor.clear();console.log(interceptor.isEmpty); // true
Remove a specific handler by ID
Handler ID to remove
const id = interceptor.use(handler);interceptor.reject(id); // Remove the handler Copy
const id = interceptor.use(handler);interceptor.reject(id); // Remove the handler
Generic interceptor for processing items with middleware pattern
Example