카테고리 페이지에 파일 목록 부분 구현

This commit is contained in:
static
2025-01-21 17:32:08 +09:00
parent efe2782db0
commit 88d4757cf7
9 changed files with 201 additions and 2 deletions

View File

@@ -13,6 +13,7 @@ import {
} from "$lib/indexedDB";
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
import type {
CategoryFileListResponse,
CategoryInfoResponse,
DirectoryInfoResponse,
FileInfoResponse,
@@ -56,6 +57,7 @@ export type CategoryInfo =
dataKeyVersion?: undefined;
name?: undefined;
subCategoryIds: number[];
files?: undefined;
}
| {
id: number;
@@ -63,6 +65,7 @@ export type CategoryInfo =
dataKeyVersion?: Date;
name: string;
subCategoryIds: number[];
files: number[];
};
const directoryInfoStore = new Map<DirectoryId, Writable<DirectoryInfo | null>>();
@@ -235,7 +238,7 @@ const fetchCategoryInfoFromServer = async (
info: Writable<CategoryInfo | null>,
masterKey: CryptoKey,
) => {
const res = await callGetApi(`/api/category/${id}`);
let res = await callGetApi(`/api/category/${id}`);
if (res.status === 404) {
info.set(null);
return;
@@ -251,12 +254,20 @@ const fetchCategoryInfoFromServer = async (
const { dataKey } = await unwrapDataKey(metadata!.dek, masterKey);
const name = await decryptString(metadata!.name, metadata!.nameIv, dataKey);
res = await callGetApi(`/api/category/${id}/file/list`);
if (!res.ok) {
throw new Error("Failed to fetch category files");
}
const { files }: CategoryFileListResponse = await res.json();
info.set({
id,
dataKey,
dataKeyVersion: new Date(metadata!.dekVersion),
name,
subCategoryIds: subCategories,
files,
});
}
};

View File

@@ -17,6 +17,16 @@ export const categoryInfoResponse = z.object({
});
export type CategoryInfoResponse = z.infer<typeof categoryInfoResponse>;
export const categoryFileAddRequest = z.object({
file: z.number().int().positive(),
});
export type CategoryFileAddRequest = z.infer<typeof categoryFileAddRequest>;
export const categoryFileListResponse = z.object({
files: z.number().int().positive().array(),
});
export type CategoryFileListResponse = z.infer<typeof categoryFileListResponse>;
export const categoryCreateRequest = z.object({
parent: categoryIdSchema,
mekVersion: z.number().int().positive(),

View File

@@ -7,6 +7,7 @@ import {
type NewCategory,
} from "$lib/server/db/category";
import { IntegrityError } from "$lib/server/db/error";
import { getAllFilesByCategory, getFile, addFileToCategory } from "$lib/server/db/file";
export const getCategoryInformation = async (userId: number, categoryId: CategoryId) => {
const category = categoryId !== "root" ? await getCategory(userId, categoryId) : undefined;
@@ -27,6 +28,35 @@ export const getCategoryInformation = async (userId: number, categoryId: Categor
};
};
export const addCategoryFile = async (userId: number, categoryId: number, fileId: number) => {
const category = await getCategory(userId, categoryId);
const file = await getFile(userId, fileId);
if (!category) {
error(404, "Invalid category id");
} else if (!file) {
error(404, "Invalid file id");
}
try {
await addFileToCategory(fileId, categoryId);
} catch (e) {
if (e instanceof IntegrityError && e.message === "File already added to category") {
error(400, "File already added");
}
throw e;
}
};
export const getCategoryFiles = async (userId: number, categoryId: number) => {
const category = await getCategory(userId, categoryId);
if (!category) {
error(404, "Invalid category id");
}
const files = await getAllFilesByCategory(userId, categoryId);
return { files: files.map(({ id }) => id) };
};
export const createCategory = async (params: NewCategory) => {
const oneMinuteAgo = new Date(Date.now() - 60 * 1000);
const oneMinuteLater = new Date(Date.now() + 60 * 1000);

View File

@@ -5,6 +5,7 @@
import { getCategoryInfo, type CategoryInfo } from "$lib/modules/filesystem";
import { masterKeyStore } from "$lib/stores";
import CreateCategoryModal from "./CreateCategoryModal.svelte";
import Files from "./Files.svelte";
import SubCategories from "./SubCategories.svelte";
import { requestCategoryCreation } from "./service";
@@ -34,7 +35,7 @@
<TopBar title={$info?.name} xPadding />
{/if}
{#if $info}
<div class="flex-grow space-y-4 bg-gray-100">
<div class="flex-grow space-y-4 bg-gray-100 pb-[5.5em]">
<div class="space-y-4 bg-white p-4">
{#if data.id !== "root"}
<p class="text-lg font-bold text-gray-800">하위 카테고리</p>
@@ -52,6 +53,9 @@
{#if data.id !== "root"}
<div class="space-y-4 bg-white p-4">
<p class="text-lg font-bold text-gray-800">파일</p>
{#key $info}
<Files info={$info} onFileClick={({ id }) => goto(`/file/${id}`)} />
{/key}
</div>
{/if}
</div>

View File

@@ -0,0 +1,61 @@
<script lang="ts">
import type { Writable } from "svelte/store";
import type { FileInfo } from "$lib/modules/filesystem";
import type { SelectedFile } from "./service";
import IconDraft from "~icons/material-symbols/draft";
import IconMoreVert from "~icons/material-symbols/more-vert";
interface Props {
info: Writable<FileInfo | null>;
onclick: (selectedFile: SelectedFile) => void;
}
let { info, onclick }: Props = $props();
const openFile = () => {
const { id, dataKey, dataKeyVersion, name } = $info as FileInfo;
if (!dataKey || !dataKeyVersion) return; // TODO: Error handling
setTimeout(() => {
onclick({ id, dataKey, dataKeyVersion, name });
}, 100);
};
const openMenu = (e: Event) => {
e.stopPropagation();
// TODO
};
</script>
{#if $info}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div id="button" onclick={openFile} class="h-12 rounded-xl">
<div id="button-content" class="flex h-full items-center gap-x-4 p-2 transition">
<div class="flex-shrink-0 text-lg text-blue-400">
<IconDraft />
</div>
<p title={$info.name} class="flex-grow truncate font-medium">
{$info.name}
</p>
<button
id="open-menu"
onclick={openMenu}
class="flex-shrink-0 rounded-full p-1 active:bg-gray-100"
>
<IconMoreVert class="text-lg" />
</button>
</div>
</div>
{/if}
<style>
#button:active:not(:has(#open-menu:active)) {
@apply bg-gray-100;
}
#button-content:active:not(:has(#open-menu:active)) {
@apply scale-95;
}
</style>

View File

@@ -0,0 +1,34 @@
<script lang="ts">
import type { Writable } from "svelte/store";
import { getFileInfo, type FileInfo, type CategoryInfo } from "$lib/modules/filesystem";
import { masterKeyStore } from "$lib/stores";
import File from "./File.svelte";
import type { SelectedFile } from "./service";
interface Props {
info: CategoryInfo;
onFileClick: (file: SelectedFile) => void;
}
let { info, onFileClick }: Props = $props();
let files: Writable<FileInfo | null>[] = $state([]);
$effect(() => {
files =
info.files?.map((id) => {
const info = getFileInfo(id, $masterKeyStore?.get(1)?.key!);
return info;
}) ?? [];
// TODO: Sorting
});
</script>
<div class="space-y-1">
{#each files as file}
<File info={file} onclick={onFileClick} />
{:else}
<p class="text-gray-800">이 카테고리에 추가된 파일이 없어요.</p>
{/each}
</div>

View File

@@ -10,6 +10,13 @@ export interface SelectedSubCategory {
name: string;
}
export interface SelectedFile {
id: number;
dataKey: CryptoKey;
dataKeyVersion: Date;
name: string;
}
export const requestCategoryCreation = async (
name: string,
parentId: "root" | number,

View File

@@ -0,0 +1,25 @@
import { error, text } from "@sveltejs/kit";
import { z } from "zod";
import { authorize } from "$lib/server/modules/auth";
import { categoryFileAddRequest } from "$lib/server/schemas";
import { addCategoryFile } from "$lib/server/services/category";
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ locals, params, request }) => {
const { userId } = await authorize(locals, "activeClient");
const paramsZodRes = z
.object({
id: z.coerce.number().int().positive(),
})
.safeParse(params);
if (!paramsZodRes.success) error(400, "Invalid path parameters");
const { id } = paramsZodRes.data;
const bodyZodRes = categoryFileAddRequest.safeParse(await request.json());
if (!bodyZodRes.success) error(400, "Invalid request body");
const { file } = bodyZodRes.data;
await addCategoryFile(userId, id, file);
return text("File added", { headers: { "Content-Type": "text/plain" } });
};

View File

@@ -0,0 +1,17 @@
import { error, json } from "@sveltejs/kit";
import { z } from "zod";
import { authorize } from "$lib/server/modules/auth";
import { categoryFileListResponse, type CategoryFileListResponse } from "$lib/server/schemas";
import { getCategoryFiles } from "$lib/server/services/category";
import type { RequestHandler } from "./$types";
export const GET: RequestHandler = async ({ locals, params }) => {
const { userId } = await authorize(locals, "activeClient");
const zodRes = z.object({ id: z.coerce.number().int().positive() }).safeParse(params);
if (!zodRes.success) error(400, "Invalid path parameters");
const { id } = zodRes.data;
const { files } = await getCategoryFiles(userId, id);
return json(categoryFileListResponse.parse({ files }) as CategoryFileListResponse);
};