Skip to content

Commit

Permalink
rm manager for some asset routes
Browse files Browse the repository at this point in the history
  • Loading branch information
dromzeh committed Mar 12, 2024
1 parent 8a92705 commit c965db7
Show file tree
Hide file tree
Showing 6 changed files with 186 additions and 65 deletions.
27 changes: 11 additions & 16 deletions src/v2/routes/asset/delete/id/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,23 @@
import { OpenAPIHono } from "@hono/zod-openapi"
import { deleteAssetByIdRoute } from "./openapi"
import { getConnection } from "@/v2/db/turso"
import { AssetManager } from "@/v2/lib/managers/asset/asset-manager"
import { eq } from "drizzle-orm"
import { asset } from "@/v2/db/schema"

const handler = new OpenAPIHono<{ Bindings: Bindings; Variables: Variables }>()

handler.openapi(deleteAssetByIdRoute, async (ctx) => {
const assetId = ctx.req.valid("param").id

if (isNaN(parseInt(assetId))) {
return ctx.json(
{
success: false,
message: "Invalid asset ID",
},
400
)
}

const { drizzle } = await getConnection(ctx.env)
const assetManager = new AssetManager(drizzle)
const asset = await assetManager.getAssetById(parseInt(assetId))

if (!asset) {
const [existingAsset] = await drizzle
.select({ id: asset.id })
.from(asset)
.where(eq(asset.id, parseInt(assetId)))
.limit(1)

if (!existingAsset) {
return ctx.json(
{
success: true,
Expand All @@ -32,8 +27,8 @@ handler.openapi(deleteAssetByIdRoute, async (ctx) => {
)
}

await assetManager.deleteAssetById(parseInt(assetId))
await ctx.env.FILES_BUCKET.delete(asset.url)
await drizzle.delete(asset).where(eq(asset.id, parseInt(assetId)))
// await ctx.env.FILES_BUCKET.delete(asset.url)

return ctx.json(
{
Expand Down
56 changes: 38 additions & 18 deletions src/v2/routes/asset/get/id/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,45 @@
import { OpenAPIHono } from "@hono/zod-openapi"
import { getAssetByIdRoute } from "./openapi"
import { getConnection } from "@/v2/db/turso"
import { AssetManager } from "@/v2/lib/managers/asset/asset-manager"
import { asset } from "@/v2/db/schema"
import { eq, sql } from "drizzle-orm"

const handler = new OpenAPIHono<{ Bindings: Bindings; Variables: Variables }>()

handler.openapi(getAssetByIdRoute, async (ctx) => {
const assetId = ctx.req.valid("param").id

if (isNaN(parseInt(assetId))) {
return ctx.json(
{
success: false,
message: "Invalid asset ID",
},
400
)
}

const parsedAssetId = parseInt(assetId)

const { drizzle } = await getConnection(ctx.env)
const assetManager = new AssetManager(drizzle)
const asset = await assetManager.getAssetById(parsedAssetId)

if (!asset) {
const foundAsset = await drizzle.query.asset.findFirst({
where: (asset, { eq }) => eq(asset.id, parseInt(assetId)),
with: {
assetTagAsset: {
with: {
assetTag: true,
},
},
authUser: {
columns: {
id: true,
avatarUrl: true,
displayName: true,
username: true,
usernameColour: true,
pronouns: true,
verified: true,
bio: true,
dateJoined: true,
isSupporter: true,
role: true,
},
},
game: true,
assetCategory: true,
},
})

if (!foundAsset) {
return ctx.json(
{
success: false,
Expand All @@ -34,12 +49,17 @@ handler.openapi(getAssetByIdRoute, async (ctx) => {
)
}

await assetManager.updateAssetViews(parsedAssetId)
await drizzle
.update(asset)
.set({
viewCount: sql`${asset.viewCount} + 1`,
})
.where(eq(asset.id, parseInt(assetId)))

return ctx.json(
{
success: true,
asset,
asset: foundAsset,
},
200
)
Expand Down
61 changes: 50 additions & 11 deletions src/v2/routes/asset/modify/id/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { OpenAPIHono } from "@hono/zod-openapi"
import { getConnection } from "@/v2/db/turso"
import { modifyAssetRoute } from "./openapi"
import { AuthSessionManager } from "@/v2/lib/managers/auth/user-session-manager"
import { AssetManager } from "@/v2/lib/managers/asset/asset-manager"
import { asset } from "@/v2/db/schema"
import { eq } from "drizzle-orm"
import { asset, assetTag, assetTagAsset } from "@/v2/db/schema"
import { and, eq } from "drizzle-orm"
import { SplitQueryByCommas } from "@/v2/lib/helpers/split-query-by-commas"

const handler = new OpenAPIHono<{ Bindings: Bindings; Variables: Variables }>()

Expand Down Expand Up @@ -37,7 +37,6 @@ handler.openapi(modifyAssetRoute, async (ctx) => {
}

const { drizzle } = getConnection(ctx.env)
const assetManager = new AssetManager(drizzle)

const [assetUser] = await drizzle
.select({
Expand All @@ -56,17 +55,57 @@ handler.openapi(modifyAssetRoute, async (ctx) => {
)
}

const updatedAsset = await assetManager.updateAssetById(parseInt(id), {
name,
tags,
assetCategoryId,
gameId,
})
await drizzle
.update(asset)
.set({
name,
assetCategoryId,
gameId,
})
.where(eq(asset.id, parseInt(id)))
.returning()

const newTags = SplitQueryByCommas(tags) ?? []

const oldTags = await drizzle
.select({
assetTagId: assetTag.id,
})
.from(assetTagAsset)
.innerJoin(assetTag, eq(assetTag.id, assetTagAsset.assetTagId))
.where(eq(assetTagAsset.assetId, parseInt(id)))

const oldTagIds = oldTags.map((t) => t.assetTagId)
const tagsToRemove = oldTagIds.filter((t) => !newTags.includes(t))
const tagsToAdd = newTags.filter((t) => !oldTagIds.includes(t))

const tagBatchQueries = [
...tagsToRemove.map((tagId) =>
drizzle
.delete(assetTagAsset)
.where(
and(
eq(assetTagAsset.assetId, parseInt(id)),
eq(assetTagAsset.assetTagId, tagId)
)
)
),
...tagsToAdd.map((tag) =>
drizzle.insert(assetTagAsset).values({
assetId: parseInt(id),
assetTagId: tag,
})
),
]

// https://github.com/drizzle-team/drizzle-orm/issues/1301
type TagBatchQuery = (typeof tagBatchQueries)[number]

await drizzle.batch(tagBatchQueries as [TagBatchQuery, ...TagBatchQuery[]])

return ctx.json(
{
success: true,
asset: updatedAsset,
},
200
)
Expand Down
2 changes: 0 additions & 2 deletions src/v2/routes/asset/modify/id/[id]/schema.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { z } from "zod"
import { selectAssetSchema } from "@/v2/db/schema"

export const modifyAssetPathSchema = z.object({
id: z.string().openapi({
Expand Down Expand Up @@ -47,5 +46,4 @@ export const modifyAssetSchema = z.object({

export const modifyAssetResponseSchema = z.object({
success: z.literal(true),
game: selectAssetSchema,
})
50 changes: 47 additions & 3 deletions src/v2/routes/asset/search/all/route.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,58 @@
import { OpenAPIHono } from "@hono/zod-openapi"
import { assetSearchAllFilterRoute } from "./openapi"
import { getConnection } from "@/v2/db/turso"
import { AssetManager } from "@/v2/lib/managers/asset/asset-manager"
import { sql, and, or, like, eq } from "drizzle-orm"

Check failure on line 4 in src/v2/routes/asset/search/all/route.ts

View workflow job for this annotation

GitHub Actions / ESLint

'sql' is defined but never used

Check failure on line 4 in src/v2/routes/asset/search/all/route.ts

View workflow job for this annotation

GitHub Actions / ESLint

'and' is defined but never used

Check failure on line 4 in src/v2/routes/asset/search/all/route.ts

View workflow job for this annotation

GitHub Actions / ESLint

'or' is defined but never used

Check failure on line 4 in src/v2/routes/asset/search/all/route.ts

View workflow job for this annotation

GitHub Actions / ESLint

'like' is defined but never used

Check failure on line 4 in src/v2/routes/asset/search/all/route.ts

View workflow job for this annotation

GitHub Actions / ESLint

'eq' is defined but never used
import { SplitQueryByCommas } from "@/v2/lib/helpers/split-query-by-commas"

const handler = new OpenAPIHono<{ Bindings: Bindings; Variables: Variables }>()

handler.openapi(assetSearchAllFilterRoute, async (ctx) => {
const { drizzle } = await getConnection(ctx.env)
const assetManager = new AssetManager(drizzle)
const assets = await assetManager.searchAssets(ctx.req.valid("query"))

const { name, game, category, tags, offset } = ctx.req.valid("query")

const gameList = game ? SplitQueryByCommas(game.toLowerCase()) : null
const categoryList = category
? SplitQueryByCommas(category.toLowerCase())
: null
const searchQuery = name ?? null
const tagList = tags ? SplitQueryByCommas(tags.toLowerCase()) : null

// is this bad for performance? probably
const assets = await drizzle.query.asset.findMany({
where: (asset, { and, or, like, eq, sql }) =>
and(
tagList && tagList.length > 0
? or(
...tagList.map(
(t) =>
sql`EXISTS (SELECT 1 FROM assetTagAsset WHERE assetTagAsset.asset_id = ${asset.id} AND assetTagAsset.asset_tag_id = ${t})`
)
)
: undefined,
searchQuery ? like(asset.name, `%${searchQuery}%`) : undefined,
gameList
? or(...gameList.map((game) => eq(asset.gameId, game)))
: undefined,
categoryList
? or(
...categoryList.map((category) =>
eq(asset.assetCategoryId, category)
)
)
: undefined,
eq(asset.status, "approved")
),
limit: 100,
offset: offset ? parseInt(offset) : 0,
with: {
assetTagAsset: {
with: {
assetTag: true,
},
},
},
})

return ctx.json(
{
Expand Down
55 changes: 40 additions & 15 deletions src/v2/routes/asset/upload/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { OpenAPIHono } from "@hono/zod-openapi"
import { uploadAssetRoute } from "./openapi"
import { AuthSessionManager } from "@/v2/lib/managers/auth/user-session-manager"
import { AssetManager } from "@/v2/lib/managers/asset/asset-manager"
import { getConnection } from "@/v2/db/turso"
import { SplitQueryByCommas } from "@/v2/lib/helpers/split-query-by-commas"
import { assetTagAsset } from "@/v2/db/schema"
const handler = new OpenAPIHono<{ Bindings: Bindings; Variables: Variables }>()

handler.openapi(uploadAssetRoute, async (ctx) => {
Expand Down Expand Up @@ -38,26 +39,50 @@ handler.openapi(uploadAssetRoute, async (ctx) => {
}

const { drizzle } = getConnection(ctx.env)
const assetManager = new AssetManager(drizzle)

const newAsset = await assetManager.createAsset(
user.id,
user.username,
{
name,
tags,
assetCategoryId,
gameId,
assetIsSuggestive,
},
ctx.env.FILES_BUCKET,
asset as File
const { key } = await ctx.env.FILES_BUCKET.put(
`/assets/${gameId}/${assetCategoryId}/${name}.png`,
asset
)

const createdAsset = await drizzle
.insert(asset)
.values({
name: name,
extension: "png",
gameId: gameId,
assetCategoryId: assetCategoryId,
url: key,
uploadedByName: user.username,
uploadedById: user.id,
status: "pending",
fileSize: 0,
width: 0,
height: 0,
assetIsSuggestive: Boolean(assetIsSuggestive),
})
.returning()

const tagsSplit = SplitQueryByCommas(tags) ?? []

if (tagsSplit.length > 0) {
const tagBatchQueries = tagsSplit.map((tag) =>
drizzle.insert(assetTagAsset).values({
assetId: createdAsset[0].id,
assetTagId: tag,
})
)

type TagBatchQuery = (typeof tagBatchQueries)[number]
await drizzle.batch(
tagBatchQueries as [TagBatchQuery, ...TagBatchQuery[]]
)
}

return ctx.json(
{
success: true,
asset: newAsset,
asset: createdAsset[0],
},
200
)
Expand Down

0 comments on commit c965db7

Please sign in to comment.