generated from oveddan/scaffold-eth-ts-tailwind
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ipfsSceneSaver.ts
111 lines (90 loc) · 2.47 KB
/
ipfsSceneSaver.ts
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { CIDString } from "web3.storage";
import { SceneConfiguration, StoredSceneAndFiles } from "../../types/scene";
import { SceneFilesLocal } from "../../types/shared";
import {
extractFilesToUploadAndLocations,
filterUndefined,
} from "../sceneParser";
import { makeWeb3StorageClient } from "./web3Storage";
export const metadataFileName = "metadata.json";
// source: https://stackoverflow.com/questions/12168909/blob-from-dataurl
async function dataURItoBlob(dataURI: string) {
return await (await fetch(dataURI)).blob();
}
export const createImageFromDataUri = async (
dataUri: string,
fileName: string
) => {
const blob = await dataURItoBlob(dataUri);
const file = new File([blob], fileName);
return file;
};
export const createJsonFileFromObject = (object: Object, fileName: string) => {
const fileContents = JSON.stringify(object);
const blob = new Blob([fileContents], { type: "application/json" });
const file = new File([blob], fileName);
return file;
};
export const makeIpfsSceneFiles = async ({
scene,
files,
forkedFrom,
sceneImage,
}: {
scene: SceneConfiguration;
files: SceneFilesLocal;
forkedFrom?: string;
sceneImage?: File;
}) => {
const { sceneFiles: storedFileLocations, toUpload } =
extractFilesToUploadAndLocations({ scene, files });
const storedSceneAndFiles: StoredSceneAndFiles = {
scene,
files: storedFileLocations,
forkedFrom,
};
const sceneConfigMetadata = createJsonFileFromObject(
storedSceneAndFiles,
metadataFileName
);
return {
sceneConfigMetadata,
sceneAssetsToUpload: toUpload,
};
};
const toFileInIpfsFolder = (cid: CIDString, file: File | undefined) => {
if (!file) return undefined;
return `ipfs://${cid}/${file.name}`;
};
export const saveSceneToIpfs = async ({
scene,
files,
sceneImage,
forkedFrom,
}: {
scene: SceneConfiguration;
files: SceneFilesLocal;
sceneImage?: File;
forkedFrom?: string;
}) => {
const { sceneConfigMetadata, sceneAssetsToUpload } = await makeIpfsSceneFiles(
{ scene, files, forkedFrom }
);
const allFiles = filterUndefined([
sceneConfigMetadata,
...sceneAssetsToUpload,
sceneImage,
]);
const client = makeWeb3StorageClient();
const cid = await client.put(allFiles);
const sceneGraphFileUrl = toFileInIpfsFolder(
cid,
sceneConfigMetadata
) as string;
const sceneImageUrl = toFileInIpfsFolder(cid, sceneImage);
return {
cid,
sceneGraphFileUrl,
sceneImageUrl: sceneImageUrl,
};
};