현재 카테고리에 파일이 존재하지 않으면 하위 카테고리에 있는 파일 목록이 가져와지지 않던 버그 수정

This commit is contained in:
static
2025-01-22 23:14:32 +09:00
parent dd0a887576
commit a1fbea3e45

View File

@@ -1,4 +1,4 @@
import { sql } from "kysely"; import { sql, type NotNull } from "kysely";
import pg from "pg"; import pg from "pg";
import { IntegrityError } from "./error"; import { IntegrityError } from "./error";
import db from "./kysely"; import db from "./kysely";
@@ -299,27 +299,34 @@ export const getAllFilesByCategory = async (
const files = await db const files = await db
.withRecursive("cte", (db) => .withRecursive("cte", (db) =>
db db
.selectFrom("file") .selectFrom("category")
.innerJoin("file_category", "file.id", "file_category.file_id") .leftJoin("file_category", "category.id", "file_category.category_id")
.selectAll("file_category") .select(["id", "parent_id", "user_id", "file_category.file_id"])
.select(sql<number>`0`.as("depth")) .select(sql<number>`0`.as("depth"))
.where("user_id", "=", userId) .where("id", "=", categoryId)
.where("category_id", "=", categoryId)
.$if(recursive, (qb) => .$if(recursive, (qb) =>
qb.unionAll((db) => qb.unionAll((db) =>
db db
.selectFrom("file") .selectFrom("category")
.innerJoin("file_category", "file.id", "file_category.file_id") .leftJoin("file_category", "category.id", "file_category.category_id")
.innerJoin("category", "file_category.category_id", "category.id") .innerJoin("cte", "category.parent_id", "cte.id")
.innerJoin("cte", "category.parent_id", "cte.category_id") .select([
.selectAll("file_category") "category.id",
.select(sql<number>`cte.depth + 1`.as("depth")) "category.parent_id",
.where("file.user_id", "=", userId), "category.user_id",
"file_category.file_id",
])
.select(sql<number>`cte.depth + 1`.as("depth")),
), ),
), ),
) )
.selectFrom("cte") .selectFrom("cte")
.select(["file_id", "depth"]) .select(["file_id", "depth"])
.distinctOn("file_id")
.where("user_id", "=", userId)
.where("file_id", "is not", null)
.$narrowType<{ file_id: NotNull }>()
.orderBy(["file_id", "depth"])
.execute(); .execute();
return files.map(({ file_id, depth }) => ({ id: file_id, isRecursive: depth > 0 })); return files.map(({ file_id, depth }) => ({ id: file_id, isRecursive: depth > 0 }));
}; };