Effect.gen
https://effect.website/docs/getting-started/using-generators/
pipe(Effect) を用いて処理を組み立てると、ステップが多くなるにつれて 可読性 が低下することがある
code:ts
const main = fetchRequest.pipe(
Effect.filterOrFail(
(response) => response.ok,
(): FetchError => new FetchError(),
),
Effect.flatMap(jsonResponse),
Effect.catchTags({
FetchError: () => Effect.succeed("Fetch error"),
JsonError: () => Effect.succeed("Json error"),
}),
);
これを Effect.gen を用いると、従来の TypeScript の構文のように記述することが可能となる
code:ts
const main = Effect.gen(function* () {
const response = yield* fetchRequest;
if (!response.ok) return yield* new FetchError();
return yield* jsonResponse(response);
});
このコードは async / await のコードを、以下のように変換したものと近しい
async を Effect.gen に置き換える
無名関数をジェネレータ関数に置き換える
await と throw を yield* に置き換える
code:ts
const main = async () => {
const response = await fetchRequest();
if (!response.ok) throw new FetchError()
return await jsonResponse(response);
};
Effect.gen は JavaScript の ジェネレータ と イテレータ の プロトコル を組み合わせて、関数内の各ステップでエラーや成功を追跡できるようにしている
#Effect(TypeScript)