diff options
| author | MohamedBassem <me@mbassem.com> | 2024-03-19 02:21:54 +0000 |
|---|---|---|
| committer | MohamedBassem <me@mbassem.com> | 2024-03-19 02:23:04 +0000 |
| commit | aa7d68a00cbe9d7d3733f4cd02061d4586af061c (patch) | |
| tree | c4382ba683b5245f2bfeb0c3595f8768f39cc905 /packages/shared/assetdb.ts | |
| parent | 785a5b574992296e187a66412dd42f7b4a686353 (diff) | |
| download | karakeep-aa7d68a00cbe9d7d3733f4cd02061d4586af061c.tar.zst | |
refactor: Change asset storage to be the filesystem instead of sqlite
Diffstat (limited to 'packages/shared/assetdb.ts')
| -rw-r--r-- | packages/shared/assetdb.ts | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/packages/shared/assetdb.ts b/packages/shared/assetdb.ts new file mode 100644 index 00000000..0840eec2 --- /dev/null +++ b/packages/shared/assetdb.ts @@ -0,0 +1,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}); +} |
