summaryrefslogtreecommitdiff
path: root/apps/web/src/services/storage/migrations/transformers/v0-to-v1.ts
blob: d2259b646db112a5c90c77f86a10f760aa1495b7 (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
82
83
import { buildDefaultScene } from "@/lib/scenes";
import type { SerializedScene } from "@/services/storage/types";
import type { TScene } from "@/types/timeline";
import type { MigrationResult, ProjectRecord } from "./types";

export interface TransformV0ToV1Options {
	now?: Date;
}

export function transformProjectV0ToV1({
	project,
	options = {},
}: {
	project: ProjectRecord;
	options?: TransformV0ToV1Options;
}): MigrationResult<ProjectRecord> {
	const { now = new Date() } = options;

	const scenesValue = project.scenes;
	if (Array.isArray(scenesValue) && scenesValue.length > 0) {
		return { project, skipped: true, reason: "already has scenes" };
	}

	const mainScene = buildDefaultScene({ isMain: true, name: "Main scene" });
	const serializedScene = serializeScene({ scene: mainScene });
	const updatedProject: ProjectRecord = {
		...project,
		scenes: [serializedScene],
		currentSceneId: mainScene.id,
		version: 1,
	};

	const updatedAt = now.toISOString();
	if (isRecord(project.metadata)) {
		updatedProject.metadata = {
			...project.metadata,
			updatedAt,
		};
	} else {
		updatedProject.updatedAt = updatedAt;
	}

	return { project: updatedProject, 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 serializeScene({ scene }: { scene: TScene }): SerializedScene {
	return {
		id: scene.id,
		name: scene.name,
		isMain: scene.isMain,
		tracks: scene.tracks,
		bookmarks: scene.bookmarks,
		createdAt: scene.createdAt.toISOString(),
		updatedAt: scene.updatedAt.toISOString(),
	};
}

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