实现说明
底层就是函数 classifyOutcome。
使用要点
- 没有从任何仓库拉取东西;语言自带用到的全部 API。
- 每一步打印都带着自己的标签:
transport failure:、slow timeout:、transient status:。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 classifyOutcome。
入口签名:function classifyOutcome(res: UpstreamOutcome)
核心语句
return 'reject';
return 'retry';
return 'ok';
代码示例
type UpstreamOutcome =
| { kind: 'http'; status: number; body: string }
| { kind: 'timeout'; elapsedMs: number }
| { kind: 'network'; code: string };
function classifyOutcome(res: UpstreamOutcome): 'retry' | 'ok' | 'reject' {
// switch (true) narrows `res` inside each case body based on its predicate
switch (true) {
case res.kind === 'network':
console.log('transport failure:', res.code);
return 'retry';
case res.kind === 'timeout' && res.elapsedMs >= 1000:
console.log('slow timeout:', res.elapsedMs);
return 'retry';
case res.kind === 'http' && (res.status === 429 || res.status >= 500):
console.log('transient status:', res.status);
return 'retry';
case res.kind === 'http' && res.status >= 200 && res.status < 300:
return 'ok';
default:
return 'reject';
}
}
const samples: UpstreamOutcome[] = [
{ kind: 'http', status: 200, body: 'ok' },
{ kind: 'http', status: 503, body: 'busy' },
{ kind: 'timeout', elapsedMs: 1500 },
{ kind: 'http', status: 400, body: 'bad input' },
{ kind: 'network', code: 'ECONNRESET' },
];
console.log('decisions:', samples.map(classifyOutcome).join(','));