samedi 9 avril 2022

Bridge between incompatible implementations in typescript

I'm trying to create a bridge between two services with an incompatible interface.

ServiceType is an argument from the user, so it has to be validated during runtime.

The best I could think of is this. But there are several problems. I will have to create a similar method like find on the SericeByType object for each function on CampaignService | LeadService and the result from that function is a union of CampaignModel | LeadModel.

Is there a better way how to do it?

interface CampaignModel {
  id: number
}

class CampaignService {
  public async find(startId: number, limit: number): Promise<CampaignModel[]> {
    return [];
  }
}

interface LeadModel {
  id: string
}

class LeadService {
  public async find(startId: string, limit: number): Promise<LeadModel[]> {
    return [];
  }
}

type ServiceType = 'Campaign' | 'Lead'

class SericeByType {
  private readonly campaignService: CampaignService = new CampaignService();
  private readonly leadService: LeadService = new LeadService();

  public async find(type: ServiceType, startId: number | string, limit: number) {
    if (this.isCampaign(type)) {
      return this.campaignService.find(startId as number, limit);
    } else if (this.isLead(type)) {
      return this.leadService.find(startId as string, limit);
    } else {
      throw new Error();
    }
  }

  private isCampaign(type: ServiceType) {
    return type === 'Campaign';
  }

  private isLead(type: ServiceType) {
    return type === 'Lead';
  }
}

const service = new SericeByType();
service.find('Campaign', 16, 10);
service.find('Lead', 'xxxawf', 10);

Playground

Aucun commentaire:

Enregistrer un commentaire