aboutsummaryrefslogtreecommitdiffstats
path: root/packages/shared/assetdb.ts
blob: 0840eec24cd6a023581ef329c537848fa3dff653 (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
import * as fs from "fs";
import * as path from "path";
import { z } from "zod";

import serverConfig from "./config";

const ROOT_PATH = path.join(serverConfig.dataDir, "assets");

function getAssetDir(userId: string, assetId: string) {
  return path.join(ROOT_PATH, userId, assetId);
}

export const zAssetMetadataSchema = z.object({
  contentType: z.string(),
});

export async function saveAsset({
  userId,
  assetId,
  asset,
  metadata,
}: {
  userId: string;
  assetId: string;
  asset: Buffer,
  metadata: z.infer<typeof zAssetMetadataSchema>;
}) {
  const assetDir = getAssetDir(userId, assetId);
  await fs.promises.mkdir(assetDir, { recursive: true });

  await Promise.all([
    fs.promises.writeFile(path.join(assetDir, "asset.bin"), asset),
    fs.promises.writeFile(path.join(assetDir, "metadata.json"), JSON.stringify(metadata)),
  ]);
}

export async function readAsset({
  userId,
  assetId,
}: {
  userId: string;
  assetId: string;
}) {
  const assetDir = getAssetDir(userId, assetId);
  
  const [asset, metadataStr] =  await Promise.all([
    fs.promises.readFile(path.join(assetDir, "asset.bin")),
    fs.promises.readFile(path.join(assetDir, "metadata.json"), {encoding: "utf8"}),
  ]);

  const metadata = zAssetMetadataSchema.parse(JSON.parse(metadataStr));
  return {asset, metadata};
}

export async function deleteAsset({
  userId,
  assetId,
}: {
  userId: string;
  assetId: string;
}) {
  const assetDir = getAssetDir(userId, assetId);
  await fs.promises.rm(path.join(assetDir), {recursive: true});
}