summaryrefslogtreecommitdiff
path: root/apps/web/src/services/storage/migrations/__tests__/helpers.ts
blob: 381cb9354f135ea8a3ed40aabda0d658eb36376b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * Type-safe accessors for navigating migration output.
 *
 * Migrations input/output `Record<string, unknown>` because they handle
 * potentially malformed data from older versions. Tests need to inspect
 * specific properties of the migrated result without using type assertions.
 *
 * These helpers narrow through type guards (Array.isArray + a record
 * predicate), so the file contains no unsafe assertions despite turning
 * unknown into concrete shapes.
 */

function describe(value: unknown): string {
	if (value === null) return "null";
	if (Array.isArray(value)) return "array";
	return typeof value;
}

function isRecord(value: unknown): value is Record<string, unknown> {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}

export function asRecord(value: unknown): Record<string, unknown> {
	if (!isRecord(value)) {
		throw new Error(`Expected record, got ${describe(value)}`);
	}
	return value;
}

export function asArray(value: unknown): unknown[] {
	if (!Array.isArray(value)) {
		throw new Error(`Expected array, got ${describe(value)}`);
	}
	return value;
}

export function asRecordArray(value: unknown): Record<string, unknown>[] {
	return asArray(value).map(asRecord);
}