Exhaustive switch true For Multi-Rule Routing
Combine ordered predicates and type guards inside switch (true) to narrow union events and numeric thresholds without deeply nested if-else chains.
Code
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(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
transient status: 503
slow timeout: 1500
transport failure: ECONNRESET
decisions: ok,retry,retry,reject,retryHow the snippet works
Exhaustive switch true For Multi-Rule Routing keeps everything in the function classifyOutcome.
Points of care
- Copy, run: the standard library answers every call in the file.
Using it
Signature: function classifyOutcome(res: UpstreamOutcome)
The run emits 4 labeled sections — transport failure:, slow timeout:, transient status:, decisions: — one per step.
Key statements
return 'reject';
return 'retry';
return 'ok';
Interactive Tools for This Topic
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.URL Pattern MatcherTest Express-style URL patterns with :param and wildcard segments against concrete paths and extract the captured parameter values.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `classifyOutcome` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.