Effect CommunityEC
Effect Community•4w ago•
4 replies
bebenzer

### Converting TypeScript Class to Effect Service with Runtime Configuration

hello 👋

I’m trying to convert a TypeScript class into an Effect way service. My issue: the service isn’t a global "singleton" I need to construct it after loading some db data, similar to how I'd normally pass arguments to a constructor.

export class PricingService implements Pricing {
    constructor(
        private readonly rules: Rule[],
        private readonly duration: Duration,
        private readonly vatComputation: VATComputation,
    ) {}

    discountedPrice(): number {
      return 0
    }
}

how should this translate to Effect.Service? since I can’t pass constructor arguments when yielding the tag, I thought of using a PricingServiceConfig
class PricingServiceConfig extends Effect.Service<PricingServiceConfig>()("PricingServiceConfig", {
    succeed: {
        rules: someRules,
        duration: someDuration,
        vatComputation: someVATComputation,
    }
}){}

export class PricingService extends Effect.Service<PricingService>()("PricingService", {
    dependencies: [PricingServiceConfig.Default],
    effect: Effect.gen(function*(){
        const config = yield* PricingServiceConfig
    })
}){}

but I still dont see how to supply that config at runtime

for context, here’s how the current ts code works:
const getSpacePricing = (spaceId: SpaceID) => {
        const space = getSpace(spaceId)
        if (space.type === 'meeting') {
                return new MeetingPricing(space.rules, createVAT('default'))
        } else {
                return new BasicPricing(space.rules, createVAT('reduced'))
        }
}

const createInvoice = (bookingId: BookingID) => {
        const booking = getBooking(bookingId)
        const spacePricing = getSpacePricing(booking.spaceId)

        const totalPrice = spacePricing.getTotal()
        const vatPrice = spacePricing.getVat()
        const extraPrice = spacePricing.getExtra()
}
Was this page helpful?