Command Middlewares
In Seyfert middleware are functions that are called before the command is executed. You can use them to do verifications, logging, etc.
Let's create a basic middleware that logs in the command that is being executed.
Creating a middleware
This example uses console.log
to log command details, if you want to make use of the built in logger to make your logs consistant or just to have the extra decoration you can call middle.context.client.logger
.
e.g. middle.context.client.logger.info("Log message")
Now let's register the middlewares on seyfert but first we should create a file to export all our middleware
Now we can use the logger
middleware on any command.
Now every time the ping
command is executed, the logger middleware will log forward the command.
Middlewares are executed in the order in which they are added.
Stop middleware
As we had said you can use middlewares to do verifications, and you can stop the execution of the command if the verification fails.
Let's take a look adding some logic to the logger middleware.
Now every time the ping
command is executed in a DM, the logger middleware will stop the execution of the command and send the error message to the handler. Learn how to handle errors here.
Notice you can access to the interaction data using middle.context.interaction
On the other hand we could skip the interaction (ignore the interaction and literally do nothing) by using middle.pass()
Passing data
The last thing we can do with middlewares is to pass data to the command. This can be useful to avoid repeating the same code in multiple commands for example fetching data from the database.
We'll continue with the logger middleware and pass some data to the command.
Now let's modify the ping
command to receive the data.
If you want to pass data from more than one middleware you can use the |
operator, for example CommandContext<never, "logger" | "otherMiddleware">
Global Middlewares
Global middlewares follow the same rule and structure explained above, with the brief difference that they have a unique property in the context and are declared separately.