Middleware
Intercept, validate, and mutate messages using WAKit's Pipeline architecture.
The Pipeline Concept
WAKit includes a robust Pipeline engine. Unlike basic event emitters where every listener fires simultaneously, the Pipeline processes incoming messages through an ordered chain of middleware functions.
This allows you to implement things like:
- Rate Limiting: Drop messages if a user spams.
- Deduplication: Ignore duplicate messages based on their message ID.
- Authentication: Only allow admins to trigger certain commands.
- Sanitization: Automatically lower-case all command text before your logic runs.
Creating a Pipeline
Every WAKitClient has a pipeline attached to it. You can inject middleware functions using client.pipeline.use().
import { WAKitClient } from '@atharvh01/wakit';
const client = new WAKitClient({ sessionName: 'pipeline-test' });
// 1. Logger Middleware
client.pipeline.use(async (ctx, next) => {
console.log(`[${new Date().toISOString()}] Incoming message from ${ctx.message.chatId}`);
await next();
console.log(`[${new Date().toISOString()}] Finished processing message`);
});
// 2. Command Prefix Filter
client.pipeline.use(async (ctx, next) => {
if (!ctx.message.text?.startsWith('!')) {
// If it's not a command, we don't call next().
// The chain stops here.
return;
}
// Clean up the text for downstream
ctx.message.text = ctx.message.text.toLowerCase();
await next();
});
// Final handler
client.on('message', async (message) => {
// We know it starts with '!' and is lowercase because of the middleware!
if (message.text === '!stats') {
await client.sendMessage(message.chatId, { text: 'Bot is healthy!' });
}
});
How next() works
The next() function pauses the current middleware, passes control to the next middleware in the chain, and then resumes the original middleware once the chain finishes (similar to Koa or Express).
If you do NOT call next(), the pipeline aborts. No further middleware will run, and the final client.on('message') event will NOT be emitted.
[!TIP] The WAKit team plans to ship built-in middleware for common tasks (like Rate Limiting and Caching) in the upcoming v1.1.0 release!