Examples

API service

import * as DI from 'diabolo'

interface ApiService extends DI.Service<'ApiService', {
  getDog: () => Promise<string>
}> { }

const apiService = DI.createService<ApiService>('ApiService')

const apiServiceImpl = DI.lazyCreateServiceImpl<ApiService>(() => ({
  getDog: async () => {
    const response = await fetch('https://dog.ceo/api/breeds/image/random')
    const data = await response.json()
    return data.message
  }
}))

const testApiServiceImpl = DI.lazyCreateServiceImpl<ApiService>(() => ({
  getDog: async () => 'https://images.dog.ceo/breeds/terrier/norfolk/n02094114_1003.jpg'
}))

const mainFunction = DI.createFunction(function* () {
  const api = yield * DI.requireService(apiService)
  const dog = api.getDog()
  return dog
})

const dog = DI.provide(mainFunction, {
  ApiService: apiServiceImpl
})()

if (import.meta.vitest) {
  const { expect, it } = import.meta.vitest
  it('should get a dog', async () => {
    const dog = await DI.provide(mainFunction, {
      ApiService: testApiServiceImpl
    })()
    expect(dog).toBe('https://images.dog.ceo/breeds/terrier/norfolk/n02094114_1003.jpg')
  })
}