feat: connect guarded asset import api
This commit is contained in:
1 parent
3497df9dfd
commit
eb759f54bf
26 files changed
+2342
-24
No files matched your search
@@ -0,0 +1,72 @@
|
||||
import { withAdmin } from '@/lib/api-handler'
|
||||
import { apiError } from '@/lib/api-response'
|
||||
import { PERMS } from '@/lib/permissions'
|
||||
import { logAudit } from '@/lib/services/audit'
|
||||
import { cloneSingleFurni, fetchSourceFurnidata } from '@/lib/services/clone-import'
|
||||
import { getSource } from '@/lib/services/clone-sources'
|
||||
import { runSseBatch } from '@/lib/services/import/core/sse-batch'
|
||||
|
||||
interface BatchItem {
|
||||
classname: string
|
||||
}
|
||||
|
||||
export const POST = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request, ctx) => {
|
||||
const body = await request.json()
|
||||
const sourceId: string = body.sourceId || ''
|
||||
const rawClassnames: string[] = body.classnames || []
|
||||
|
||||
if (!sourceId) return apiError('Missing sourceId', 400)
|
||||
if (rawClassnames.length === 0) return apiError('No classnames to clone', 400)
|
||||
|
||||
const source = await getSource(sourceId)
|
||||
if (!source) return apiError('Source not found', 404)
|
||||
|
||||
// Fetch furnidata once so we can resolve entries by classname.
|
||||
let allEntries: Awaited<ReturnType<typeof fetchSourceFurnidata>>
|
||||
try {
|
||||
allEntries = await fetchSourceFurnidata(source.furnidataUrl)
|
||||
} catch (err) {
|
||||
return apiError(`Failed to fetch furnidata: ${(err as Error).message}`, 502)
|
||||
}
|
||||
|
||||
const entryMap = new Map(allEntries.map((e) => [e.classname, e]))
|
||||
|
||||
// Deduplicate classnames preserving order.
|
||||
const seen = new Set<string>()
|
||||
const items: BatchItem[] = []
|
||||
for (const cn of rawClassnames) {
|
||||
if (!seen.has(cn)) {
|
||||
seen.add(cn)
|
||||
items.push({ classname: cn })
|
||||
}
|
||||
}
|
||||
|
||||
if (items.length > 500) return apiError('Too many classnames (max 500)', 400)
|
||||
|
||||
return runSseBatch<BatchItem>({
|
||||
items,
|
||||
concurrency: body.concurrency || 2,
|
||||
labelOf: (it) => it.classname,
|
||||
worker: async (it, _index, report) => {
|
||||
const entry = entryMap.get(it.classname)
|
||||
if (!entry) {
|
||||
return { ok: false, error: 'classname not found in source furnidata' }
|
||||
}
|
||||
|
||||
const result = await cloneSingleFurni({ source, entry, onProgress: report })
|
||||
|
||||
if (result.ok) {
|
||||
logAudit({
|
||||
userId: ctx.session.user.id,
|
||||
action: 'clone_furni',
|
||||
target: 'FurniAsset',
|
||||
targetId: 0,
|
||||
after: { classname: it.classname, sourceId, sourceName: source.name },
|
||||
})
|
||||
}
|
||||
|
||||
return { ok: result.ok, warnings: result.warnings, error: result.error }
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user