Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

network-config.ts

48 lines1.5 KB

1import { createStore, useStore } from "@/lib/store";
2​
3/**
4 * How the fake network behaves. The browser toolbar's latency and failure
5 * controls (the app sheet's Network view on phones) write to this store; in
6 * dev it's also on the console: `__fakeApi.setNetworkConfig({ latencyMs: 2000 })`.
7 */
8export interface NetworkConfig {
9 /** How long every request takes, in milliseconds. */
10 latencyMs: number;
11 /** Fail the next request sent with a 500, then switch back off. Requests already in flight aren't affected. */
12 failNextRequest: boolean;
13 /** Share of requests (0 to 1) that fail at random. */
14 failureRate: number;
16​
17export const DEFAULT_NETWORK_CONFIG: NetworkConfig = {
18 latencyMs: 500,
19 failNextRequest: false,
20 failureRate: 0,
21};
22​
23export const networkConfigStore = createStore<NetworkConfig>(DEFAULT_NETWORK_CONFIG);
24​
25export function getNetworkConfig(): NetworkConfig {
26 return networkConfigStore.get();
28​
29export function setNetworkConfig(changes: Partial<NetworkConfig>) {
30 networkConfigStore.set((config) => ({ ...config, ...changes }));
32​
33export function useNetworkConfig(): NetworkConfig {
34 return useStore(networkConfigStore);
36​
37/**
38 * Decides whether a request should fail, and consumes "fail next request".
39 * `random` is injectable for tests.
40 */
41export function takeInjectedFailure(random: () => number = Math.random): boolean {
42 const { failNextRequest, failureRate } = getNetworkConfig();
43 if (failNextRequest) {
44 setNetworkConfig({ failNextRequest: false });
45 return true;
46 }
47 return failureRate > 0 && random() < failureRate;