【发布时间】:2020-12-08 16:41:00
【问题描述】:
我们能否让 DTO 成为验证的真实来源,并在控制器和服务中使用它? 如果我已经有 DTO,为什么还需要接口?
【问题讨论】:
-
“替换所有接口”是什么意思?
标签: nestjs
我们能否让 DTO 成为验证的真实来源,并在控制器和服务中使用它? 如果我已经有 DTO,为什么还需要接口?
【问题讨论】:
标签: nestjs
如果您不想使用接口,则不需要接口。对于作为基本模型的 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);
}
}
【讨论】: