メインコンテンツへスキップ

Documentation Index

Fetch the complete documentation index at: https://docs.wyrly.dev/llms.txt

Use this file to discover all available pages before exploring further.

この guide では、Wyrly の最小構成を示します。型付きポート、具体的な実装、use case、リクエスト風スコープの 4 要素を使います。

Token を作る

トークンは、インターフェースベースの依存関係を実行時でも型安全に保つために使います。
import { createContainer, Injectable, token } from "@wyrly/core";

interface User {
  id: string;
}

interface UserRepository {
  findById(id: string): Promise<User | null>;
}

const UserRepositoryToken = token<UserRepository>("UserRepository");

Use case を定義する

@Injectable は依存関係を明示的に宣言します。Wyrly はコンストラクタのパラメーター型を実行時に読み取りません。
@Injectable({
  deps: [UserRepositoryToken],
  lifetime: "scoped",
})
class GetUserUseCase {
  constructor(private readonly users: UserRepository) {}

  execute(id: string) {
    return this.users.findById(id);
  }
}

プロバイダーを登録する

具体的な実装は composition root で登録します。
class InMemoryUserRepository implements UserRepository {
  async findById(id: string): Promise<User | null> {
    return { id };
  }
}

const container = createContainer();

container.register(UserRepositoryToken, {
  useClass: InMemoryUserRepository,
  lifetime: "scoped",
});

container.register(GetUserUseCase);

スコープから解決する

リクエスト単位の処理では scope を作り、リクエストが終わったら破棄します。
const scope = container.createScope();

try {
  const usecase = scope.resolve(GetUserUseCase);
  const user = await usecase.execute("user-1");
  console.log(user);
} finally {
  await scope.dispose();
}

グラフを検証する

テストや CI で検証を実行すると、プロバイダーの不足やライフタイムの問題を早期に検出できます。
const result = container.validate();

if (!result.ok) {
  throw new Error(result.issues.map((issue) => issue.message).join("\n"));
}

次のステップ