freshyo/packages/db_helper_sqlite/src/helper_methods/upload-url.ts
2026-10-10 19:56:02 +05:30

40 lines
1.3 KiB
TypeScript

import { and, eq, inArray } from 'drizzle-orm'
import { db } from '../db/db_index'
import { uploadUrlStatus } from '../db/schema'
export async function createUploadUrlStatus(key: string): Promise<void> {
await db.insert(uploadUrlStatus).values({
key,
status: 'pending',
})
}
export async function claimUploadUrlStatus(key: string): Promise<boolean> {
const result = await db
.update(uploadUrlStatus)
.set({ status: 'claimed' })
.where(and(eq(uploadUrlStatus.key, key), eq(uploadUrlStatus.status, 'pending')))
.returning()
return result.length > 0
}
/**
* Of the given keys, the ones that still exist with status 'pending' — i.e. uploads that
* were issued by the app and have not been attached to anything yet. Callers use this to
* reject unknown/reused upload URLs *before* writing rows that would otherwise be orphaned
* when the later claim fails.
*/
export async function getPendingUploadUrlKeys(keys: string[]): Promise<string[]> {
const unique = [...new Set(keys.filter(Boolean))]
if (unique.length === 0) {
return []
}
const rows = await db
.select({ key: uploadUrlStatus.key })
.from(uploadUrlStatus)
.where(and(inArray(uploadUrlStatus.key, unique), eq(uploadUrlStatus.status, 'pending')))
return rows.map((row) => row.key)
}