封装方法装饰器 - Typescript

问题描述 投票:0回答:1

所以我对于为我的应用程序开发自己的装饰器还相当陌生。 我正在开发一个 Discordjs 机器人,使用 Nestjs 作为后端,并使用 Necord 作为库来使用装饰器注册斜杠命令。

我想修改 Necord 的方法装饰器

@SlashCommand
的行为,它允许您为不和谐机器人注册斜杠命令。该命令采用一些参数,例如命令名称。我想修改这个装饰器以在每次执行命令时在控制台中记录信息,但不幸的是我做不到。

所以我尝试使用这些代码行创建自己的装饰器:

import { SlashCommand } from 'necord';

// Log decorator
export function Log(name: any) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        // Calls the SlashCommand decorator to register the command
        const originalMethod: any = SlashCommand(name)(target, propertyKey, descriptor);

        descriptor.value = function (...args: any[]) {
            console.log('[SlashCommand] Calling slash command: ' + name);
            return originalMethod.apply(this, args);
        };
        // Return the method
        return descriptor;
    };
}

命令要么没有正确记录到discord.js,要么根本没有记录,具体取决于我的尝试。我尝试了此装饰器的几种变体,例如在描述符重新定义之后调用 SlashCommand 装饰器并返回它,但没有任何效果符合我想要的方式。

我希望我的装饰器以与原始 necord 装饰器相同的方式工作,只需将日志添加到控制台即可。我还想用它来注册带有不和谐参数的命令。

typescript discord.js nestjs decorator
1个回答
0
投票

您可以使用 NestJS 拦截器

© www.soinside.com 2019 - 2024. All rights reserved.