提供者选项
您可以在实例化 Provider
时提供各种选项来修改其行为。
retryOptions
通过 Provider
对 fuel 节点的调用将在无法建立连接时失败。 指定重试选项允许您在最终抛出错误之前自定义处理此失败情况的方式。
注意:仅当无法建立连接时才会重试。如果建立了连接并且节点抛出错误,则不会进行重试。
您可以提供以下设置:
maxRetries
- 在初始尝试失败之后在失败调用之前重试的次数。backoff
- 用于定义尝试之间间隔的策略。exponential
(默认): 每次尝试都会加倍延迟。linear
- 每次尝试都会线性增加延迟。fixed
: 尝试之间使用固定延迟。
baseDelay
(默认 150ms) - 回退策略的基本时间(以毫秒为单位)。
ts
await Provider.create(FUEL_NETWORK_URL, {
retryOptions: {
maxRetries: 5,
baseDelay: 100,
backoff: 'linear',
},
});
1
2
3
4
5
6
7
2
3
4
5
6
7
requestMiddleware
允许您修改请求对象以添加额外的标头、修改请求的正文等。
ts
// 同步请求中间件
await Provider.create(FUEL_NETWORK_URL, {
requestMiddleware: (request: RequestInit) => {
request.credentials = 'omit';
return request;
},
});
// 同步请求中间件
await Provider.create(FUEL_NETWORK_URL, {
requestMiddleware: async (request: RequestInit) => {
const credentials = await fetchSomeExternalCredentials();
request.headers ??= {};
(request.headers as Record<string, string>).auth = credentials;
return request;
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
timeout
指定以毫秒为单位的超时时间,在此超时后,每个请求都将被中止。
ts
await Provider.create(FUEL_NETWORK_URL, {
timeout: 30000, // 如果请求需要30秒才能完成,是否会中止
});
1
2
3
2
3
fetch
提供一个自定义的 fetch
函数,该函数将替换默认的 fetch 调用。
注意:如果定义了 fetch
,则 requestMiddleware
、timeout
和 retryOptions
也将应用于此自定义的 fetch
函数。
ts
await Provider.create(FUEL_NETWORK_URL, {
fetch: async (url: string, requestInit: RequestInit | undefined) => {
// 干一些事情
await sleep(100);
// 原生 fetch 请求
const response = await fetch(url, requestInit);
const updatedResponse = decorateResponseWithCustomLogic(response);
return updatedResponse;
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13