获取
效果- 内在获取, 并有结构化的货币和流式响应支持 .
安装
npm install @effectionx/fetch effection
使用量
import { main } from "effection";
import { fetch } from "@effectionx/fetch";
await main(function* () {
let users = yield* fetch("https://api.example.com/users").json();
console.log(users);
});
流利的 API
直接打开的链路方法 fetch() 用于简洁的一行:
// JSON
let data = yield* fetch("https://api.example.com/users").json();
// Text
let html = yield* fetch("https://example.com").text();
// With validation - throws HttpError on non-2xx
let data = yield* fetch("https://api.example.com/users").expect().json();
传统 API
你也可以先得到反应,然后消耗身体:
let response = yield* fetch("https://api.example.com/users");
let data = yield* response.json();
精简应对机构
import { each } from "effection";
import { fetch } from "@effectionx/fetch";
function* example() {
for (let chunk of yield* each(fetch("https://example.com/large-file.bin").body())) {
console.log(chunk.length);
yield* each.next();
}
}
同时提出的请求
import { all } from "effection";
import { fetch } from "@effectionx/fetch";
function* fetchMultiple() {
let [users, posts, comments] = yield* all([
fetch("https://api.example.com/users").json(),
fetch("https://api.example.com/posts").json(),
fetch("https://api.example.com/comments").json(),
]);
return { users, posts, comments };
}
解析时验证 JSON
import { fetch } from "@effectionx/fetch";
interface User {
id: string;
name: string;
}
function parseUser(value: unknown): User {
if (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value
) {
return value as User;
}
throw new Error("invalid user payload");
}
function* getUser() {
return yield* fetch("https://api.example.com/user").json(parseUser);
}
处理非-2xx回复
import { HttpError, fetch } from "@effectionx/fetch";
function* getUser(id: string) {
try {
return yield* fetch(`https://api.example.com/users/${id}`).expect().json();
} catch (error) {
if (error instanceof HttpError) {
console.error(error.status, error.statusText);
}
throw error;
}
}
API 密码
fetch(input, init?)
回返a FetchOperation 既支持流利的连锁,也支持传统使用.
input- URL 字符串,URL对象,或Request对象init- 可选FetchInit选项(与RequestInit但是没有signal(中文(简体) )
取消是通过Evicion结构的货币自动处理的. 当
范围退出,飞行中请求中止。 已经解决的本地采集是
离开完好无损。 这个 signal 选项被故意省略,因为 Effection 管理
为你取消.
FetchOperation
可链取操作返回 fetch()。 。 。 .
json<T>(), (中文(简体) ),json<T>(parse)- 解析反应为JSONtext()- 作为文本获得回复arrayBuffer()- 获得响应作为阵列缓冲器blob()- 作为Blob得到回应formData()- 作为FormData获得响应body()- 溪流反应机构:Stream<Uint8Array, void>expect()- 返回一个新的FetchOperation抛出HttpError关于非-2xx的
也可以直接得到一个 FetchResponse数字 :
let response = yield* fetch("https://api.example.com/users");
FetchResponse
效果包绕本地 Response 与基于操作的身体读取器.
json<T>(), (中文(简体) ),json<T>(parse)text()arrayBuffer()blob()formData()body(): Stream<Uint8Array, void>expect()- 掷出HttpError非-2xx回复raw- 接触当地人Response