|
| 1 | +/** |
| 2 | + * Interface of a data source for type `T`. |
| 3 | + */ |
| 4 | +export type Source<T> = { |
| 5 | + /** |
| 6 | + * Invalidate the current data. |
| 7 | + */ |
| 8 | + invalidate: () => void; |
| 9 | + /** |
| 10 | + * Source is no longer required and can be cleaned up. |
| 11 | + */ |
| 12 | + done: () => void; |
| 13 | + /** |
| 14 | + * Current state of the data. |
| 15 | + * |
| 16 | + * - `unknown`: State of data is not currently known. |
| 17 | + * |
| 18 | + * - `error`: An error occurred while fetching the data. |
| 19 | + * |
| 20 | + * - `valid`: The data is up-to-date. |
| 21 | + * |
| 22 | + * - `stale`: The data has been invalidated, and is waiting to be |
| 23 | + * re-fetched. |
| 24 | + */ |
| 25 | + state: "error" | "stale" | "unknown" | "valid"; |
| 26 | + /** |
| 27 | + * Loading state of the source. |
| 28 | + */ |
| 29 | + loading: boolean; |
| 30 | + /** |
| 31 | + * Latest version of the data. If the source hasn't provided any |
| 32 | + * data yet, then it will be `null`. |
| 33 | + * |
| 34 | + * @note This will always have the latest value, even if it has been |
| 35 | + * invalidated or is currently being fetched. |
| 36 | + */ |
| 37 | + data: null | T; |
| 38 | + /** |
| 39 | + * Current error of the source, if present. |
| 40 | + */ |
| 41 | + error: { |
| 42 | + /** |
| 43 | + * User-friendly description of the error. |
| 44 | + */ |
| 45 | + message: string; |
| 46 | + /** |
| 47 | + * Underlying error object. |
| 48 | + */ |
| 49 | + source: unknown; |
| 50 | + } | null; |
| 51 | + /** |
| 52 | + * Callback subscription for source events. |
| 53 | + * |
| 54 | + * - `data`: called when new data is available. |
| 55 | + * |
| 56 | + * - `error`: called when an error has occurred. |
| 57 | + * |
| 58 | + * - `load`: called when a load begins, and is provided promise |
| 59 | + * which will resolve with the loaded data, or reject with an |
| 60 | + * error. |
| 61 | + */ |
| 62 | + on: <Name extends keyof Events<T>>( |
| 63 | + event: Name, |
| 64 | + cb: (...data: Events<T>[Name]) => void, |
| 65 | + ) => UnsubscribeCallback; |
| 66 | +}; |
| 67 | + |
| 68 | +/** |
| 69 | + * Map of all event types available on a source. |
| 70 | + */ |
| 71 | +export type Events<T> = { |
| 72 | + data: [data: T]; |
| 73 | + error: [message: string, source: unknown]; |
| 74 | + load: [result: Promise<T>]; |
| 75 | +}; |
| 76 | + |
| 77 | +/** |
| 78 | + * A callback function to unsubscribe from some event. |
| 79 | + */ |
| 80 | +type UnsubscribeCallback = () => void; |
0 commit comments