【问题标题】:NestJs: Why we don't use DTOs to replace all interfaces?NestJs:为什么我们不使用 DTO 来替换所有接口?
【发布时间】:2020-12-08 16:41:00
【问题描述】:

我们能否让 DTO 成为验证的真实来源,并在控制器和服务中使用它? 如果我已经有 DTO,为什么还需要接口?

【问题讨论】:

  • “替换所有接口”是什么意思?

标签: nestjs


【解决方案1】:

如果您不想使用接口,则不需要接口。对于作为基本模型的 DTO,我也不使用接口。话虽如此,它们真的很强大,所以我绝对不会阻止你使用它们,举个例子:

interface ILogger {
    log(message: string) : Promise<void>;
}

class ConsoleLogger implements ILogger {
    log(message: string) : Promise<void> {
        return Promise.resolve(console.log(message));
    }
}

class DatabaseLogger implements ILogger {

    private dbConnection;

    constructor() {
        dbConnection = new DBConnection(); //Fake but it drives the point across 
    }

    async log(message: string) : Promise<void> {
        return await this.dbConnection.saveLog(message);
    }
}

class DoTheThing {

    private _logger: ILogger;

    //You can have nest inject the best logger for this situation and your code doesn't have to care
    //about the actual implementation :)
    constructor(logger: ILogger) {
        this._logger = logger;
    }

    async myMethod() {
        const tweetMessage = await sendTweet('...');
        this._logger.log(tweetMessage);
    }
}

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 2021-09-28
    • 2020-12-02
    • 2021-11-09
    • 2010-10-13
    • 1970-01-01
    • 2015-05-15
    • 2013-04-28
    • 1970-01-01
    相关资源
    最近更新 更多