Categories
Tags
Ai 生成 API学习 API简化 api请求 API调用 best-practices Blogging Caching catchTag catchTags class CLI Config context Context Context.Tag CSS Customization Demo development DocC Docker dual API Effect effect Effect.Service Effect.succeed Example extension ffmpeg filterOrFail flatMap Fuwari gen generator grep hooks HTML HTTP响应 IDE自动补全 iOS javascript JavaScript Javascript Layer.effect Layer.provide Layers Linux Markdown Mock n8n Next.js ParseError pipe pokemon PostCSS process.env progress Promise promise provideService PWA react React React Hook Form React Query React Router react-native Scheduler Schema Schema.Class security Service Worker Services SSR state-management suspense Tagged Errors TaggedError TanStack Query TanStack Start tips tryPromise tsconfig TypeScript typescript Video VS Code vscode Web API Web Development yield yt-dlp Zod 不透明类型 二叉树 代码组织 任务调度 优先级 使用服务 依赖注入 依赖管理 值语义 入门教程 最佳实践 最小堆 函数式编程 函数组合 前端 前端开发 副作用 副作用控制 可视化 可组合性 可维护性 可访问性 命令行 响应过滤 多个错误 实现 实践指南 层 层依赖 层组合 工具链 并发控制 应用架构 延迟执行 开发技巧 开发教程 开源 异步处理 异步操作 异步编程 性能优化 手写系列 排序 接口设计 插件开发 数据结构 数据获取 数据解码 数据验证 无限滚动 日历 日志分析 服务 服务依赖 服务定义 服务实现 服务提供 测试 源码分析 状态管理 环境变量 生成器 离线支持 程序分离 算法 类型安全 类型定义 类型推断 类型系统 类定义 线性代码 组合 翻译 自动化 自定义错误 表单验证 记忆化 设计模式 语义化 运维 运行时验证 部分应用 配置 配置变量 配置服务 配置管理 重构 错误处理 错误定义 错误恢复 项目设置
533 words
3 minutes
[Effect Layers] 10. 从Effect.Service提取默认层
从Effect.Service提取默认层
https://github.com/typeonce-dev/effect-getting-started-course
最后,我们也可以重构 PokeApi:
const make = Effect.gen(function* () {
const pokemonCollection = yield* PokemonCollection;
const buildPokeApiUrl = yield* BuildPokeApiUrl;
return {
getPokemon: Effect.gen(function* () {
const requestUrl = buildPokeApiUrl({ name: pokemonCollection[0] });
const response = yield* Effect.tryPromise({
try: () => fetch(requestUrl),
catch: () => new FetchError(),
});
if (!response.ok) {
return yield* new FetchError();
}
const json = yield* Effect.tryPromise({
try: () => response.json(),
catch: () => new JsonError(),
});
return yield* Schema.decodeUnknown(Pokemon)(json);
}),
};
});
export class PokeApi extends Context.Tag("PokeApi")<
PokeApi,
Effect.Effect.Success<typeof make>
>() {
static readonly Live = Layer.effect(this, make).pipe(
Layer.provide(Layer.mergeAll(PokemonCollection.Live, BuildPokeApiUrl.Live))
);
}由于服务被定义为 Effect(使用 Layer.effect),我们使用 effect:
export class PokeApi extends Effect.Service<PokeApi>()("PokeApi", {
effect: Effect.gen(function* () {
const pokemonCollection = yield* PokemonCollection;
const buildPokeApiUrl = yield* BuildPokeApiUrl;
return {
getPokemon: Effect.gen(function* () {
const requestUrl = buildPokeApiUrl({ name: pokemonCollection[0] });
const response = yield* Effect.tryPromise({
try: () => fetch(requestUrl),
catch: () => new FetchError(),
});
if (!response.ok) {
return yield* new FetchError();
}
const json = yield* Effect.tryPromise({
try: () => response.json(),
catch: () => new JsonError(),
});
return yield* Schema.decodeUnknown(Pokemon)(json);
}),
};
}),
}) {}然后我们还添加 dependencies 来提供所需的服务。
使用 Effect.Service 定义的 class 具有一个 Default 属性,该属性包含提供了所有依赖的默认层。
我们从 PokemonCollection 和 BuildPokeApiUrl 中使用它:
export class PokeApi extends Effect.Service<PokeApi>()("PokeApi", {
effect: Effect.gen(function* () {
const pokemonCollection = yield* PokemonCollection;
const buildPokeApiUrl = yield* BuildPokeApiUrl;
return {
getPokemon: Effect.gen(function* () {
const requestUrl = buildPokeApiUrl({ name: pokemonCollection[0] });
const response = yield* Effect.tryPromise({
try: () => fetch(requestUrl),
catch: () => new FetchError(),
});
if (!response.ok) {
return yield* new FetchError();
}
const json = yield* Effect.tryPromise({
try: () => response.json(),
catch: () => new JsonError(),
});
return yield* Schema.decodeUnknown(Pokemon)(json);
}),
};
}),
dependencies: [PokemonCollection.Default, BuildPokeApiUrl.Default],
}) {}NOTEDefaultWithoutDependencies
Effect.Service还有一个DefaultWithoutDependencies属性,该属性包含不包含依赖的默认层(例如BuildPokeApiUrl.DefaultWithoutDependencies)。
我们在 MainLayer 中也提取 PokeApi.Default 来完成对 Effect.Service 的重构:
index.ts
import { Effect, Layer } from "effect";
import { PokeApi } from "./PokeApi";
const MainLayer = Layer.mergeAll(PokeApi.Default);
export const program = Effect.gen(function* () {
const pokeApi = yield* PokeApi;
return yield* pokeApi.getPokemon;
});
const runnable = program.pipe(Effect.provide(MainLayer));
const main = runnable.pipe(
Effect.catchTags({
FetchError: () => Effect.succeed("Fetch error"),
JsonError: () => Effect.succeed("Json error"),
ParseError: () => Effect.succeed("Parse error"),
})
);
Effect.runPromise(main).then(console.log);现在应用程序的工作方式与之前相同,但使用了更具表现力的API,代码行数更少。
所有这些 Layer 和 Config 的优势是什么?
这种实现使所有服务都具有可组合性。我们将在下一个关于测试的模块中看到可组合性的实际应用 🚀
[Effect Layers] 10. 从Effect.Service提取默认层
https://0bipinnata0.my/posts/course/effect-beginners-complete-getting-started/layers/10-extracting-default-layer-from-effect-service/