Heather Lau
Heather Lau

Reputation: 15

NestJs: Why we don't use DTOs to replace all interfaces?

Can we make DTOs source of truth for the validations, and use it in both controller and service? If I already have DTOs, why do I need interfaces ?

Upvotes: 0

Views: 381

Answers (1)

nerdy beast
nerdy beast

Reputation: 789

You don't need interfaces if you don't want to use them. For DTO's which are meant to be basic models, I don't use interfaces either. That being said, they are really powerful so I'm definitely not discouraging you from using them, take this example:

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);
    }
}

Upvotes: 1

Related Questions