lundi 21 novembre 2022

Trying to implement design pattern in typescript (NestJS), but having trouble when setting variable dynamically

I am trying to implement a base service builder for injecting dependencies. Here the code I've written so far.

`

import { DirectVotesService } from 'src/direct-votes/direct-votes.service';
import { EligibleVotingCandidatesService } from 'src/eligible-voting-candidates/eligible-voting-candidates.service';
import { FederalVotesService } from 'src/federal-votes/federal-votes.service';
import { VotesService } from 'src/votes/votes.service';
import { ServiceBuilder } from '../interfaces/base-service.builder';

type VotesServiceDependencies = {
  federalVotesService: FederalVotesService;
  directVotesService: DirectVotesService;
  eligibleVotingCandidatesService: EligibleVotingCandidatesService;
};

export class VotesServiceBuilder
  implements ServiceBuilder<VotesService, VotesServiceDependencies>
{
  constructor(
    readonly service: VotesService,
    private readonly dependencies: VotesServiceDependencies
  ) {}

  getService<S extends keyof VotesServiceDependencies>(
    serviceKey: S
  ): VotesServiceDependencies[S] {
    return this.dependencies[serviceKey];
  }

  setService<S extends keyof VotesServiceDependencies>(serviceKey: S): this {
    this.service[serviceKey] = this.dependencies[serviceKey];
    return this;
  }

  build(): VotesService {
    return this.service;
  }
}

` But I am getting an TS error when setting the service. The error:

`

Type 'VotesServiceDependencies[S]' is not assignable to type 'VotesService[S]'.
  Type 'VotesServiceDependencies' is missing the following properties from type 'VotesService': repository, provinceClusterService, statesService, campaignsService, and 8 more.ts(2322)

` error I would like the setService method to set the service to the respective properties and chain them as follows. For example:

this.votesBuilderService.setService("federalVotesService").setService("directVotesService")

Also, the VotesService itself:

`

export class VotesService {
  /* Set these services from the votes service builder */
  federalVotesService: FederalVotesService;
  directVotesService: DirectVotesService;
  eligibleVotingCandidatesService: EligibleVotingCandidatesService;
  constructor(
    @InjectRepository(VotesRepository)
    private readonly repository: VotesRepository,
    private readonly campaignsService: CampaignsService,
    @Inject(CACHE_MANAGER) private readonly cacheManager: Cache
  ) {}
}

`

Aucun commentaire:

Enregistrer un commentaire