Skip to content

Commit

Permalink
replace with recursive CTE
Browse files Browse the repository at this point in the history
  • Loading branch information
adriangohjw committed Dec 25, 2024
1 parent 93f0f75 commit 39d4cd6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 33 deletions.
33 changes: 28 additions & 5 deletions apps/studio/src/server/modules/resource/resource.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import {
import { validateUserPermissionsForSite } from "../site/site.service"
import {
getBatchAncestryWithSelfQuery,
getNestedFolderChildren,
getSearchRecentlyEdited,
getSearchResults,
getSearchWithResourceIds,
Expand Down Expand Up @@ -250,10 +249,34 @@ export const resourceRouter = router({
}

return {
items: await getNestedFolderChildren({
siteId: Number(siteId),
resourceId: Number(resourceId),
}),
items: await db
.withRecursive("NestedResources", (eb) =>
eb
.selectFrom("Resource")
.select(["title", "permalink", "type", "id", "parentId"])
.where("Resource.type", "in", [ResourceType.Folder])
.where("Resource.siteId", "=", Number(siteId))
.where("Resource.parentId", "=", String(resourceId))
.unionAll((eb) =>
eb
.selectFrom("Resource")
.innerJoin(
"NestedResources",
"Resource.parentId",
"NestedResources.id",
)
.select([
"Resource.title",
"Resource.permalink",
"Resource.type",
"Resource.id",
"Resource.parentId",
]),
),
)
.selectFrom("NestedResources")
.select(["title", "permalink", "type", "id", "parentId"])
.execute(),
}
}),

Expand Down
28 changes: 0 additions & 28 deletions apps/studio/src/server/modules/resource/resource.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -691,34 +691,6 @@ export const getSearchRecentlyEdited = async ({
})
}

export const getNestedFolderChildren = async ({
siteId,
resourceId,
}: {
siteId: number
resourceId: number
}): Promise<ResourceItemContent[]> => {
return (async function getNestedChildren(
parentId: number,
): Promise<ResourceItemContent[]> {
const children = await db
.selectFrom("Resource")
.select(["title", "permalink", "type", "id", "parentId"])
.where("Resource.type", "in", [ResourceType.Folder])
.where("Resource.siteId", "=", Number(siteId))
.where("Resource.parentId", "=", String(parentId))
.execute()

const nestedChildren = await Promise.all(
children.map(async (child) => {
const childrenOfChild = await getNestedChildren(Number(child.id))
return [child, ...childrenOfChild]
}),
)
return nestedChildren.flat()
})(resourceId)
}

export const getSearchWithResourceIds = async ({
siteId,
resourceIds,
Expand Down

0 comments on commit 39d4cd6

Please sign in to comment.