카테고리 이름 변경 및 삭제, 카테고리에서 파일 삭제 구현

This commit is contained in:
static
2025-01-22 15:39:48 +09:00
parent 4c0d668cc1
commit 368868910d
20 changed files with 507 additions and 54 deletions

View File

@@ -1,4 +1,6 @@
<script lang="ts">
import type { Component } from "svelte";
import type { SvelteHTMLElements } from "svelte/elements";
import type { Writable } from "svelte/store";
import type { CategoryInfo } from "$lib/modules/filesystem";
import Category from "./Category.svelte";
@@ -6,16 +8,23 @@
interface Props {
categories: Writable<CategoryInfo | null>[];
categoryMenuIcon?: Component<SvelteHTMLElements["svg"]>;
onCategoryClick: (category: SelectedCategory) => void;
onCategoryMenuClick?: (category: SelectedCategory) => void;
}
let { categories, onCategoryClick }: Props = $props();
let { categories, categoryMenuIcon, onCategoryClick, onCategoryMenuClick }: Props = $props();
</script>
{#if categories.length > 0}
<div class="space-y-1">
{#each categories as category}
<Category info={category} onclick={onCategoryClick} />
<Category
info={category}
menuIcon={categoryMenuIcon}
onclick={onCategoryClick}
onMenuClick={onCategoryMenuClick}
/>
{/each}
</div>
{/if}

View File

@@ -1,17 +1,20 @@
<script lang="ts">
import type { Component } from "svelte";
import type { SvelteHTMLElements } from "svelte/elements";
import type { Writable } from "svelte/store";
import type { CategoryInfo } from "$lib/modules/filesystem";
import type { SelectedCategory } from "./service";
import IconCategory from "~icons/material-symbols/category";
import IconMoreVert from "~icons/material-symbols/more-vert";
interface Props {
info: Writable<CategoryInfo | null>;
menuIcon?: Component<SvelteHTMLElements["svg"]>;
onclick: (category: SelectedCategory) => void;
onMenuClick?: (category: SelectedCategory) => void;
}
let { info, onclick }: Props = $props();
let { info, menuIcon: MenuIcon, onclick, onMenuClick }: Props = $props();
const openCategory = () => {
const { id, dataKey, dataKeyVersion, name } = $info as CategoryInfo;
@@ -25,7 +28,12 @@
const openMenu = (e: Event) => {
e.stopPropagation();
// TODO
const { id, dataKey, dataKeyVersion, name } = $info as CategoryInfo;
if (!dataKey || !dataKeyVersion) return; // TODO: Error handling
setTimeout(() => {
onMenuClick!({ id, dataKey, dataKeyVersion, name });
}, 100);
};
</script>
@@ -40,13 +48,15 @@
<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>
{#if MenuIcon && onMenuClick}
<button
id="open-menu"
onclick={openMenu}
class="flex-shrink-0 rounded-full p-1 active:bg-gray-100"
>
<MenuIcon class="text-lg" />
</button>
{/if}
</div>
</div>
{/if}

View File

@@ -1,5 +1,6 @@
<script lang="ts">
import type { ClassValue } from "svelte/elements";
import type { Component } from "svelte";
import type { ClassValue, SvelteHTMLElements } from "svelte/elements";
import type { Writable } from "svelte/store";
import { EntryButton } from "$lib/components/buttons";
import { getCategoryInfo, type CategoryInfo } from "$lib/modules/filesystem";
@@ -13,14 +14,18 @@
info: CategoryInfo;
onSubCategoryClick: (subCategory: SelectedCategory) => void;
onSubCategoryCreateClick: () => void;
onSubCategoryMenuClick?: (category: SelectedCategory) => void;
subCategoryCreatePosition?: "top" | "bottom";
subCategoryMenuIcon?: Component<SvelteHTMLElements["svg"]>;
}
let {
info,
onSubCategoryClick,
onSubCategoryCreateClick,
onSubCategoryMenuClick,
subCategoryCreatePosition = "bottom",
subCategoryMenuIcon,
...props
}: Props = $props();
@@ -49,7 +54,12 @@
{@render subCategoryCreate()}
{/if}
{#key info}
<Categories categories={subCategories} onCategoryClick={onSubCategoryClick} />
<Categories
categories={subCategories}
categoryMenuIcon={subCategoryMenuIcon}
onCategoryClick={onSubCategoryClick}
onCategoryMenuClick={onSubCategoryMenuClick}
/>
{/key}
{#if subCategoryCreatePosition === "bottom"}
{@render subCategoryCreate()}

View File

@@ -1,33 +1,33 @@
<script lang="ts">
import type { Writable } from "svelte/store";
import {
getFileInfo,
getCategoryInfo,
type FileInfo,
type CategoryInfo,
} from "$lib/modules/filesystem";
import { getFileInfo, type FileInfo, type CategoryInfo } from "$lib/modules/filesystem";
import type { SelectedCategory } from "$lib/molecules/Categories";
import SubCategories from "$lib/molecules/SubCategories.svelte";
import { masterKeyStore } from "$lib/stores";
import File from "./File.svelte";
import type { SelectedFile } from "./service";
import IconMoreVert from "~icons/material-symbols/more-vert";
interface Props {
info: CategoryInfo;
onFileClick: (file: SelectedFile) => void;
onSubCategoryClick: (subCategory: SelectedCategory) => void;
onSubCategoryCreateClick: () => void;
onSubCategoryMenuClick: (subCategory: SelectedCategory) => void;
}
let { info, onFileClick, onSubCategoryClick, onSubCategoryCreateClick }: Props = $props();
let {
info,
onFileClick,
onSubCategoryClick,
onSubCategoryCreateClick,
onSubCategoryMenuClick,
}: Props = $props();
let subCategories: Writable<CategoryInfo | null>[] = $state([]);
let files: Writable<FileInfo | null>[] = $state([]);
$effect(() => {
subCategories = info.subCategoryIds.map((id) =>
getCategoryInfo(id, $masterKeyStore?.get(1)?.key!),
);
files = info.files?.map((id) => getFileInfo(id, $masterKeyStore?.get(1)?.key!)) ?? [];
// TODO: Sorting
@@ -39,7 +39,13 @@
{#if info.id !== "root"}
<p class="text-lg font-bold text-gray-800">하위 카테고리</p>
{/if}
<SubCategories {info} {onSubCategoryClick} {onSubCategoryCreateClick} />
<SubCategories
{info}
{onSubCategoryClick}
{onSubCategoryCreateClick}
{onSubCategoryMenuClick}
subCategoryMenuIcon={IconMoreVert}
/>
</div>
{#if info.id !== "root"}
<div class="space-y-4 bg-white p-4">

View File

@@ -136,9 +136,12 @@ export const setCategoryEncName = async (
};
export const unregisterCategory = async (userId: number, categoryId: number) => {
await db
const res = await db
.deleteFrom("category")
.where("id", "=", categoryId)
.where("user_id", "=", userId)
.execute();
.executeTakeFirst();
if (res.numDeletedRows === 0n) {
throw new IntegrityError("Category not found");
}
};

View File

@@ -27,6 +27,18 @@ export const categoryFileListResponse = z.object({
});
export type CategoryFileListResponse = z.infer<typeof categoryFileListResponse>;
export const categoryFileRemoveRequest = z.object({
file: z.number().int().positive(),
});
export type CategoryFileRemoveRequest = z.infer<typeof categoryFileRemoveRequest>;
export const categoryRenameRequest = z.object({
dekVersion: z.string().datetime(),
name: z.string().base64().nonempty(),
nameIv: z.string().base64().nonempty(),
});
export type CategoryRenameRequest = z.infer<typeof categoryRenameRequest>;
export const categoryCreateRequest = z.object({
parent: categoryIdSchema,
mekVersion: z.number().int().positive(),

View File

@@ -3,11 +3,19 @@ import {
registerCategory,
getAllCategoriesByParent,
getCategory,
setCategoryEncName,
unregisterCategory,
type CategoryId,
type NewCategory,
} from "$lib/server/db/category";
import { IntegrityError } from "$lib/server/db/error";
import { getAllFilesByCategory, getFile, addFileToCategory } from "$lib/server/db/file";
import {
getAllFilesByCategory,
getFile,
addFileToCategory,
removeFileFromCategory,
} from "$lib/server/db/file";
import type { Ciphertext } from "$lib/server/db/schema";
export const getCategoryInformation = async (userId: number, categoryId: CategoryId) => {
const category = categoryId !== "root" ? await getCategory(userId, categoryId) : undefined;
@@ -28,6 +36,17 @@ export const getCategoryInformation = async (userId: number, categoryId: Categor
};
};
export const deleteCategory = async (userId: number, categoryId: number) => {
try {
await unregisterCategory(userId, categoryId);
} catch (e) {
if (e instanceof IntegrityError && e.message === "Category not found") {
error(404, "Invalid category id");
}
throw e;
}
};
export const addCategoryFile = async (userId: number, categoryId: number, fileId: number) => {
const category = await getCategory(userId, categoryId);
const file = await getFile(userId, fileId);
@@ -57,6 +76,45 @@ export const getCategoryFiles = async (userId: number, categoryId: number) => {
return { files: files.map(({ id }) => id) };
};
export const removeCategoryFile = 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 removeFileFromCategory(fileId, categoryId);
} catch (e) {
if (e instanceof IntegrityError && e.message === "File not found in category") {
error(400, "File not added");
}
throw e;
}
};
export const renameCategory = async (
userId: number,
categoryId: number,
dekVersion: Date,
newEncName: Ciphertext,
) => {
try {
await setCategoryEncName(userId, categoryId, dekVersion, newEncName);
} catch (e) {
if (e instanceof IntegrityError) {
if (e.message === "Category not found") {
error(404, "Invalid category id");
} else if (e.message === "Invalid DEK version") {
error(400, "Invalid DEK version");
}
}
throw e;
}
};
export const createCategory = async (params: NewCategory) => {
const oneMinuteAgo = new Date(Date.now() - 60 * 1000);
const oneMinuteLater = new Date(Date.now() + 60 * 1000);

View File

@@ -0,0 +1,21 @@
import { callPostApi } from "$lib/hooks";
import { generateDataKey, wrapDataKey, encryptString } from "$lib/modules/crypto";
import type { CategoryCreateRequest } from "$lib/server/schemas";
import type { MasterKey } from "$lib/stores";
export const requestCategoryCreation = async (
name: string,
parentId: "root" | number,
masterKey: MasterKey,
) => {
const { dataKey, dataKeyVersion } = await generateDataKey();
const nameEncrypted = await encryptString(name, dataKey);
await callPostApi<CategoryCreateRequest>("/api/category/create", {
parent: parentId,
mekVersion: masterKey.version,
dek: await wrapDataKey(dataKey, masterKey.key),
dekVersion: dataKeyVersion.toISOString(),
name: nameEncrypted.ciphertext,
nameIv: nameEncrypted.iv,
});
};

View File

@@ -15,8 +15,13 @@
import { fileDownloadStatusStore, isFileDownloading, masterKeyStore } from "$lib/stores";
import AddToCategoryBottomSheet from "./AddToCategoryBottomSheet.svelte";
import DownloadStatus from "./DownloadStatus.svelte";
import { requestFileDownload, requestFileAdditionToCategory } from "./service";
import {
requestFileDownload,
requestFileAdditionToCategory,
requestFileRemovalFromCategory,
} from "./service";
import IconClose from "~icons/material-symbols/close";
import IconAddCircle from "~icons/material-symbols/add-circle";
let { data } = $props();
@@ -64,6 +69,11 @@
info = getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
};
const removeFromCategory = async (categoryId: number) => {
await requestFileRemovalFromCategory(data.id, categoryId);
info = getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
};
$effect(() => {
info = getFileInfo(data.id, $masterKeyStore?.get(1)?.key!);
isDownloadRequested = false;
@@ -135,7 +145,12 @@
<div class="space-y-2">
<p class="text-lg font-bold">카테고리</p>
<div class="space-y-1">
<Categories {categories} onCategoryClick={({ id }) => goto(`/category/${id}`)} />
<Categories
{categories}
categoryMenuIcon={IconClose}
onCategoryClick={({ id }) => goto(`/category/${id}`)}
onCategoryMenuClick={({ id }) => removeFromCategory(id)}
/>
<EntryButton onclick={() => (isAddToCategoryBottomSheetOpen = true)}>
<div class="flex h-8 items-center gap-x-4">
<IconAddCircle class="text-lg text-gray-600" />

View File

@@ -1,12 +1,13 @@
<script lang="ts">
import { onMount } from "svelte";
import type { Writable } from "svelte/store";
import { BottomSheet } from "$lib/components";
import { Button } from "$lib/components/buttons";
import { BottomDiv } from "$lib/components/divs";
import { getCategoryInfo, type CategoryInfo } from "$lib/modules/filesystem";
import SubCategories from "$lib/molecules/SubCategories.svelte";
import CreateCategoryModal from "$lib/organisms/CreateCategoryModal.svelte";
import { masterKeyStore } from "$lib/stores";
import { requestCategoryCreation } from "./service";
interface Props {
onAddToCategoryClick: (categoryId: number) => void;
@@ -17,8 +18,20 @@
let category: Writable<CategoryInfo | null> | undefined = $state();
onMount(() => {
category = getCategoryInfo("root", $masterKeyStore?.get(1)?.key!);
let isCreateCategoryModalOpen = $state(false);
const createCategory = async (name: string) => {
if (!$category) return; // TODO: Error handling
await requestCategoryCreation(name, $category.id, $masterKeyStore?.get(1)!);
isCreateCategoryModalOpen = false;
category = getCategoryInfo($category.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
};
$effect(() => {
if (isOpen) {
category = getCategoryInfo("root", $masterKeyStore?.get(1)?.key!);
}
});
</script>
@@ -30,6 +43,7 @@
info={$category}
onSubCategoryClick={({ id }) =>
(category = getCategoryInfo(id, $masterKeyStore?.get(1)?.key!))}
onSubCategoryCreateClick={() => (isCreateCategoryModalOpen = true)}
subCategoryCreatePosition="top"
/>
{#if $category.id !== "root"}
@@ -40,3 +54,5 @@
{/if}
</div>
</BottomSheet>
<CreateCategoryModal bind:isOpen={isCreateCategoryModalOpen} onCreateClick={createCategory} />

View File

@@ -1,6 +1,8 @@
import { callPostApi } from "$lib/hooks";
import { getFileCache, storeFileCache, downloadFile } from "$lib/modules/file";
import type { CategoryFileAddRequest } from "$lib/server/schemas";
import type { CategoryFileAddRequest, CategoryFileRemoveRequest } from "$lib/server/schemas";
export { requestCategoryCreation } from "$lib/services/category";
export const requestFileDownload = async (
fileId: number,
@@ -21,3 +23,11 @@ export const requestFileAdditionToCategory = async (fileId: number, categoryId:
});
return res.ok;
};
export const requestFileRemovalFromCategory = async (fileId: number, categoryId: number) => {
const res = await callPostApi<CategoryFileRemoveRequest>(
`/api/category/${categoryId}/file/remove`,
{ file: fileId },
);
return res.ok;
};

View File

@@ -3,16 +3,28 @@
import { goto } from "$app/navigation";
import { TopBar } from "$lib/components";
import { getCategoryInfo, type CategoryInfo } from "$lib/modules/filesystem";
import type { SelectedCategory } from "$lib/molecules/Categories";
import Category from "$lib/organisms/Category";
import CreateCategoryModal from "$lib/organisms/CreateCategoryModal.svelte";
import { masterKeyStore } from "$lib/stores";
import CreateCategoryModal from "./CreateCategoryModal.svelte";
import { requestCategoryCreation } from "./service";
import CategoryMenuBottomSheet from "./CategoryMenuBottomSheet.svelte";
import DeleteCategoryModal from "./DeleteCategoryModal.svelte";
import RenameCategoryModal from "./RenameCategoryModal.svelte";
import {
requestCategoryCreation,
requestCategoryRename,
requestCategoryDeletion,
} from "./service";
let { data } = $props();
let info: Writable<CategoryInfo | null> | undefined = $state();
let selectedSubCategory: SelectedCategory | undefined = $state();
let isCreateCategoryModalOpen = $state(false);
let isSubCategoryMenuBottomSheetOpen = $state(false);
let isRenameCategoryModalOpen = $state(false);
let isDeleteCategoryModalOpen = $state(false);
const createCategory = async (name: string) => {
await requestCategoryCreation(name, data.id, $masterKeyStore?.get(1)!);
@@ -39,6 +51,10 @@
info={$info}
onSubCategoryClick={({ id }) => goto(`/category/${id}`)}
onSubCategoryCreateClick={() => (isCreateCategoryModalOpen = true)}
onSubCategoryMenuClick={(subCategory) => {
selectedSubCategory = subCategory;
isSubCategoryMenuBottomSheetOpen = true;
}}
onFileClick={({ id }) => goto(`/file/${id}`)}
/>
{/if}
@@ -46,3 +62,40 @@
</div>
<CreateCategoryModal bind:isOpen={isCreateCategoryModalOpen} onCreateClick={createCategory} />
<CategoryMenuBottomSheet
bind:isOpen={isSubCategoryMenuBottomSheetOpen}
bind:selectedCategory={selectedSubCategory}
onRenameClick={() => {
isSubCategoryMenuBottomSheetOpen = false;
isRenameCategoryModalOpen = true;
}}
onDeleteClick={() => {
isSubCategoryMenuBottomSheetOpen = false;
isDeleteCategoryModalOpen = true;
}}
/>
<RenameCategoryModal
bind:isOpen={isRenameCategoryModalOpen}
bind:selectedCategory={selectedSubCategory}
onRenameClick={async (newName) => {
if (selectedSubCategory) {
await requestCategoryRename(selectedSubCategory, newName);
info = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
return true;
}
return false;
}}
/>
<DeleteCategoryModal
bind:isOpen={isDeleteCategoryModalOpen}
bind:selectedCategory={selectedSubCategory}
onDeleteClick={async () => {
if (selectedSubCategory) {
await requestCategoryDeletion(selectedSubCategory);
info = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
return true;
}
return false;
}}
/>

View File

@@ -0,0 +1,57 @@
<script lang="ts">
import { BottomSheet } from "$lib/components";
import { EntryButton } from "$lib/components/buttons";
import type { SelectedCategory } from "$lib/molecules/Categories";
import IconCategory from "~icons/material-symbols/category";
import IconEdit from "~icons/material-symbols/edit";
import IconDelete from "~icons/material-symbols/delete";
interface Props {
onRenameClick: () => void;
onDeleteClick: () => void;
isOpen: boolean;
selectedCategory: SelectedCategory | undefined;
}
let {
onRenameClick,
onDeleteClick,
isOpen = $bindable(),
selectedCategory = $bindable(),
}: Props = $props();
const closeBottomSheet = () => {
isOpen = false;
selectedCategory = undefined;
};
</script>
<BottomSheet bind:isOpen onclose={closeBottomSheet}>
<div class="w-full py-4">
{#if selectedCategory}
{@const { name } = selectedCategory}
<div class="flex h-12 items-center gap-x-4 p-2">
<div class="flex-shrink-0 text-lg">
<IconCategory />
</div>
<p title={name} class="flex-grow truncate font-semibold">
{name}
</p>
</div>
<div class="my-2 h-px w-full bg-gray-200"></div>
{/if}
<EntryButton onclick={onRenameClick}>
<div class="flex h-8 items-center gap-x-4">
<IconEdit class="text-lg" />
<p class="font-medium">이름 바꾸기</p>
</div>
</EntryButton>
<EntryButton onclick={onDeleteClick}>
<div class="flex h-8 items-center gap-x-4 text-red-500">
<IconDelete class="text-lg" />
<p class="font-medium">삭제하기</p>
</div>
</EntryButton>
</div>
</BottomSheet>

View File

@@ -0,0 +1,55 @@
<script lang="ts">
import { Modal } from "$lib/components";
import { Button } from "$lib/components/buttons";
import type { SelectedCategory } from "$lib/molecules/Categories";
interface Props {
onDeleteClick: () => Promise<boolean>;
isOpen: boolean;
selectedCategory: SelectedCategory | undefined;
}
let { onDeleteClick, isOpen = $bindable(), selectedCategory = $bindable() }: Props = $props();
const closeModal = () => {
isOpen = false;
selectedCategory = undefined;
};
const deleteEntry = async () => {
// TODO: Validation
if (await onDeleteClick()) {
closeModal();
}
};
</script>
<Modal bind:isOpen onclose={closeModal}>
{#if selectedCategory}
{@const { name } = selectedCategory}
{@const nameShort = name.length > 20 ? `${name.slice(0, 20)}...` : name}
<div class="space-y-4">
<div class="space-y-2 break-keep">
<p class="text-xl font-bold">
'{nameShort}' 카테고리를 삭제할까요?
</p>
<p>
모든 하위 카테고리도 함께 삭제돼요. <br />
하지만 카테고리에 추가된 파일들은 삭제되지 않아요.
</p>
</div>
<div class="flex gap-2">
<Button
color="gray"
onclick={() => {
isOpen = false;
}}
>
아니요
</Button>
<Button onclick={deleteEntry}>삭제할게요</Button>
</div>
</div>
{/if}
</Modal>

View File

@@ -0,0 +1,47 @@
<script lang="ts">
import { Modal } from "$lib/components";
import { Button } from "$lib/components/buttons";
import { TextInput } from "$lib/components/inputs";
import type { SelectedCategory } from "$lib/molecules/Categories";
interface Props {
onRenameClick: (newName: string) => Promise<boolean>;
isOpen: boolean;
selectedCategory: SelectedCategory | undefined;
}
let { onRenameClick, isOpen = $bindable(), selectedCategory = $bindable() }: Props = $props();
let name = $state("");
const closeModal = () => {
name = "";
isOpen = false;
selectedCategory = undefined;
};
const renameEntry = async () => {
// TODO: Validation
if (await onRenameClick(name)) {
closeModal();
}
};
$effect(() => {
if (selectedCategory) {
name = selectedCategory.name;
}
});
</script>
<Modal bind:isOpen onclose={closeModal}>
<p class="text-xl font-bold">이름 바꾸기</p>
<div class="mt-2 flex w-full">
<TextInput bind:value={name} placeholder="이름" />
</div>
<div class="mt-7 flex gap-2">
<Button color="gray" onclick={closeModal}>닫기</Button>
<Button onclick={renameEntry}>바꾸기</Button>
</div>
</Modal>

View File

@@ -1,21 +1,22 @@
import { callPostApi } from "$lib/hooks";
import { generateDataKey, wrapDataKey, encryptString } from "$lib/modules/crypto";
import type { CategoryCreateRequest } from "$lib/server/schemas";
import type { MasterKey } from "$lib/stores";
import { encryptString } from "$lib/modules/crypto";
import type { SelectedCategory } from "$lib/molecules/Categories";
import type { CategoryRenameRequest } from "$lib/server/schemas";
export const requestCategoryCreation = async (
name: string,
parentId: "root" | number,
masterKey: MasterKey,
) => {
const { dataKey, dataKeyVersion } = await generateDataKey();
const nameEncrypted = await encryptString(name, dataKey);
await callPostApi<CategoryCreateRequest>("/api/category/create", {
parent: parentId,
mekVersion: masterKey.version,
dek: await wrapDataKey(dataKey, masterKey.key),
dekVersion: dataKeyVersion.toISOString(),
name: nameEncrypted.ciphertext,
nameIv: nameEncrypted.iv,
export { requestCategoryCreation } from "$lib/services/category";
export const requestCategoryRename = async (category: SelectedCategory, newName: string) => {
const newNameEncrypted = await encryptString(newName, category.dataKey);
const res = await callPostApi<CategoryRenameRequest>(`/api/category/${category.id}/rename`, {
dekVersion: category.dataKeyVersion.toISOString(),
name: newNameEncrypted.ciphertext,
nameIv: newNameEncrypted.iv,
});
return res.ok;
};
export const requestCategoryDeletion = async (category: SelectedCategory) => {
const res = await callPostApi(`/api/category/${category.id}/delete`);
return res.ok;
};

View File

@@ -0,0 +1,20 @@
import { error, text } from "@sveltejs/kit";
import { z } from "zod";
import { authorize } from "$lib/server/modules/auth";
import { deleteCategory } from "$lib/server/services/category";
import type { RequestHandler } from "./$types";
export const POST: 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;
await deleteCategory(userId, id);
return text("Category deleted", { headers: { "Content-Type": "text/plain" } });
};

View File

@@ -0,0 +1,25 @@
import { error, text } from "@sveltejs/kit";
import { z } from "zod";
import { authorize } from "$lib/server/modules/auth";
import { categoryFileRemoveRequest } from "$lib/server/schemas";
import { removeCategoryFile } 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 = categoryFileRemoveRequest.safeParse(await request.json());
if (!bodyZodRes.success) error(400, "Invalid request body");
const { file } = bodyZodRes.data;
await removeCategoryFile(userId, id, file);
return text("File removed", { headers: { "Content-Type": "text/plain" } });
};

View File

@@ -0,0 +1,25 @@
import { error, text } from "@sveltejs/kit";
import { z } from "zod";
import { authorize } from "$lib/server/modules/auth";
import { categoryRenameRequest } from "$lib/server/schemas";
import { renameCategory } 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 = categoryRenameRequest.safeParse(await request.json());
if (!bodyZodRes.success) error(400, "Invalid request body");
const { dekVersion, name, nameIv } = bodyZodRes.data;
await renameCategory(userId, id, new Date(dekVersion), { ciphertext: name, iv: nameIv });
return text("Category renamed", { headers: { "Content-Type": "text/plain" } });
};