summaryrefslogtreecommitdiff
path: root/apps/web/src/services/storage/migrations/transformers/v2-to-v3.ts
blob: 336561097dc334a59667081ca859bb713fee4839 (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { getProjectDurationFromScenes } from "@/lib/scenes";
import type { TScene } from "@/types/timeline";
import type { MigrationResult, ProjectRecord } from "./types";

export function transformProjectV2ToV3({
	project,
}: {
	project: ProjectRecord;
}): MigrationResult<ProjectRecord> {
	const projectId = getProjectId({ project });
	if (!projectId) {
		return { project, skipped: true, reason: "no project id" };
	}

	if (isV3Project({ project })) {
		return { project, skipped: true, reason: "already v3" };
	}

	const scenes = getScenes({ project });
	const duration = getProjectDurationFromScenes({ scenes });

	const metadataValue = project.metadata;
	const metadata = isRecord(metadataValue)
		? { ...metadataValue, duration }
		: { duration };

	const migratedProject = {
		...project,
		metadata,
		version: 3,
	};

	return { project: migratedProject, skipped: false };
}

export function getProjectId({
	project,
}: {
	project: ProjectRecord;
}): string | null {
	const idValue = project.id;
	if (typeof idValue === "string" && idValue.length > 0) {
		return idValue;
	}

	const metadataValue = project.metadata;
	if (!isRecord(metadataValue)) {
		return null;
	}

	const metadataId = metadataValue.id;
	if (typeof metadataId === "string" && metadataId.length > 0) {
		return metadataId;
	}

	return null;
}

function getScenes({ project }: { project: ProjectRecord }): TScene[] {
	const scenesValue = project.scenes;
	if (!Array.isArray(scenesValue)) {
		return [];
	}

	return scenesValue.filter(isRecord) as unknown as TScene[];
}

function isV3Project({ project }: { project: ProjectRecord }): boolean {
	const versionValue = project.version;
	if (typeof versionValue === "number" && versionValue >= 3) {
		return true;
	}

	return (
		isRecord(project.metadata) && typeof project.metadata.duration === "number"
	);
}

function isRecord(value: unknown): value is ProjectRecord {
	return typeof value === "object" && value !== null;
}