Alberto AM
Alberto AM

Reputation: 320

Create a method or a service for a requirement with similar estructure

I need to create a custom LOG in my angular app (typescript). When you press some action buttons.

The body of the log is the following one:

My current implementation is the next one:

MyComponent

extraction(): void {
// bla bla bla code
this.loggerService.setMessage(setExtractionMessage());
console.log(this.loggerService.getMessage());
}

download(): void {
// bla bla bla code
this.loggerService.setMessage(setDownloadMessage());
console.log(this.loggerService.getMessage());
}

setDownloadMessage(): string {
const date = ...;
const time = ...;
const env = ...;
// same with all the constants

finalLog += date + time + env ...;
return finalLog;
} 

setExtractionMessage(): string {
const date = ...;
const time = ...;
const env = ...;
// same with all the constants

finalLog += date + time + env ...;
return finalLog;
} 

LoggerService.ts

setMessage(message: string) {
    this.message = '';
    this.message = message;
  }

  getMessage() {
    return this.message;
  }

Do have any suggestions for improving my implementation? Thanks in advance.

Upvotes: 1

Views: 55

Answers (1)

behruz
behruz

Reputation: 588

i would give more responsibilities to Logger Service. define an Enum of all types of messages, define the type of message, send the parameters and let the logger service do the job.

enum Messages: {
    extraction,
    download,
    other
}

your component:

extraction(): void {
// bla bla bla code
this.loggerService.logger(Messages.extraction, parameters);
}

download(): void {
// bla bla bla code
this.loggerService.logger(Messages.download, parameters);
}

LoggerService

logger(type, parameters: any[]){
    switch(type) {
        case Messages.extraction:
        finalLog = parameters.map(t => ''+t).join(', ');
        console.log(finalLog);
        break;

        case Messages.download:
        finalLog = parameters.map(t => ''+t).join(', ');
        console.log(finalLog);
        break;
    }
}

Upvotes: 1

Related Questions