Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

image-generation に clean architecture を導入する #90

Merged
merged 27 commits into from
Dec 1, 2024

Conversation

trpfrog
Copy link
Owner

@trpfrog trpfrog commented Dec 1, 2024

clean architecture なんもわからん、clean architecture もどきです。

  • @trpfrog.net/image-generation
    • アーキテクチャを変えました
    • wrangler types から取れる型を使うようにしました
    • テストをたくさん追加しました
  • @trpfrog.net/utils
    • 依存解決のためのユーティリティ wire 関数を作りました

@trpfrog.net/utils/wire

まだ改良の余地があるんですけどこんな感じで使えます。

services.ts

みなくても良い
export interface ImageService {
  generateImage(prompt: string): Promise<string>
}

export interface Logger {
  log(userId: string, action: string, timestamp: string): void
}

export interface TimestampProvider {
  getCurrentTimestamp(): string
}

export interface NotificationService {
  send(userId: string, message: string): Promise<string>
}

usecases.ts

みなくても良い
import { ImageService, Logger, TimestampProvider, NotificationService } from './services'

export function createImageGenerator(deps: { imageService: ImageService }) {
  return async (prompt: string): Promise<string> => {
    return await deps.imageService.generateImage(prompt)
  }
}

export function createActionLogger(deps: {
  logger: Logger
  timestampProvider: TimestampProvider
}) {
  return async (userId: string, action: string): Promise<void> => {
    const timestamp = deps.timestampProvider.getCurrentTimestamp()
    deps.logger.log(userId, action, timestamp)
  }
}

export function createUserNotifier(deps: { notificationService: NotificationService }) {
  return async (userId: string, message: string): Promise<string> => {
    return await deps.notificationService.send(userId, message)
  }
}

export function createImageProcessor(deps: {
  imageGenerator: (prompt: string) => Promise<string>
  actionLogger: (userId: string, action: string) => Promise<void>
}) {
  return async (userId: string, prompt: string): Promise<string> => {
    const image = await deps.imageGenerator(prompt)
    await deps.actionLogger(userId, `Generated image: ${image}`)
    return image
  }
}

prepare.ts

import { wire } from '@trpfrog.net/utils/wire'
import { ImageService, Logger, TimestampProvider, NotificationService } from './services'
import { createImageGenerator, createActionLogger, createUserNotifier, createImageProcessor } from './usecases'

export function prepare(deps: {
  imageService: ImageService
  logger: Logger
  timestampProvider: TimestampProvider
  notificationService: NotificationService
}) {
  return wire({
    generateImage: createImageGenerator,
    logAction: createActionLogger,
    notifyToUser: createUserNotifier,
    processImage: createImageProcessor,
  })
    .inject({
      generateImage: { imageService: deps.imageService },
      logAction: {
        logger: deps.logger,
        timestampProvider: deps.timestampProvider,
      },
      notifyToUser: { notificationService: deps.notificationService },
    })
    .inject(resolved => ({
      processImage: {
        imageGenerator: resolved.generateImage,
        actionLogger: resolved.logAction,
      },
    }))
    .build()
}

main.ts

import { prepare } from './prepare'
import { imageService, logger, timestampProvider, notificationService } from './services'

async function main() {
  const resolved = prepare({
    imageService,
    logger,
    timestampProvider,
    notificationService,
  })

  const userId = 'user123'
  const prompt = 'A futuristic cityscape at sunset'

  const image = await resolved.processImage(userId, prompt)
  console.log('Processed Image:', image)

  const notificationMessage = await resolved.notifyToUser(
    userId,
    `Your processed image "${image}" is ready!`,
  )
  console.log(notificationMessage)
}

main().catch(console.error)

これらがいい感じに型効かせてできる。べんり!

Future work

これはまだあんまり納得いってなくて将来的にはこんな感じにしたい (命名は適当)

const build = wire<{
  imageService: ImageService
  logger: Logger
  timestampProvider: TimestampProvider
  notificationService: NotificationService
}>()
  .injectTo({
    generateImage: createImageGenerator,
    logAction: createActionLogger,
    notifyToUser: createUserNotifier,
    processImage: createImageProcessor,
  })
  .inject({
    generateImage: { imageService: deps.imageService },
    logAction: {
      logger: deps.logger,
      timestampProvider: deps.timestampProvider,
    },
    notifyToUser: { notificationService: deps.notificationService },
  })
  .inject(resolved => ({
    processImage: {
      imageGenerator: resolved.generateImage,
      actionLogger: resolved.logAction,
    },
  }))
  .build
  
const resolved = build({
  imageService,
  logger,
  timestampProvider,
  notificationService,
})

Copy link

vercel bot commented Dec 1, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
trpfrog-net ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 1, 2024 10:03am

@trpfrog trpfrog merged commit 9dbfb16 into main Dec 1, 2024
3 checks passed
@trpfrog trpfrog deleted the clean-arch-image-gen branch December 1, 2024 14:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant