97 lines
3.1 KiB
TypeScript
97 lines
3.1 KiB
TypeScript
/**
|
||
* 模板列表 API
|
||
*
|
||
* 获取所有启用的模板列表(包括预制模板和自定义模板)
|
||
* 用于首页TAG筛选
|
||
*/
|
||
|
||
import { NextResponse } from 'next/server'
|
||
import { getServerSession } from 'next-auth'
|
||
import { authOptions } from '@/lib/auth'
|
||
import { prisma } from '@/lib/prisma'
|
||
import { canUseCustomTemplates, projectPublicTemplateOptionsWithPaidCore } from '@/lib/license'
|
||
import {
|
||
BUILTIN_TEMPLATE_KEYS,
|
||
createBuiltinTemplate,
|
||
} from '@/lib/upload-template-presets'
|
||
|
||
export async function GET() {
|
||
try {
|
||
const session = await getServerSession(authOptions)
|
||
if (!session?.user) {
|
||
return NextResponse.json(
|
||
{ error: '请先登录' },
|
||
{ status: 401 }
|
||
)
|
||
}
|
||
|
||
// 获取启用的预制模板列表
|
||
let enabledBuiltinTemplates: string[] = []
|
||
try {
|
||
// 使用原始 SQL 查询,避免字段不存在时的错误
|
||
const settings = await prisma.$queryRaw<Array<{ enabledBuiltinTemplates?: string | null }>>`
|
||
SELECT "enabledBuiltinTemplates" FROM "system_settings" LIMIT 1
|
||
`
|
||
if (settings[0]?.enabledBuiltinTemplates) {
|
||
const parsed = JSON.parse(settings[0].enabledBuiltinTemplates)
|
||
if (Array.isArray(parsed) && parsed.length > 0) {
|
||
enabledBuiltinTemplates = parsed
|
||
}
|
||
// 如果为空数组或null,表示全部启用,enabledBuiltinTemplates保持为空数组
|
||
}
|
||
// 如果字段不存在或为null,表示全部启用,enabledBuiltinTemplates保持为空数组
|
||
} catch (error) {
|
||
// 字段不存在或解析失败,表示全部启用
|
||
console.error('Failed to parse enabledBuiltinTemplates:', error)
|
||
}
|
||
|
||
const customTemplatesAllowed = await canUseCustomTemplates()
|
||
const customTemplates = customTemplatesAllowed
|
||
? await prisma.uploadTemplate.findMany({
|
||
select: {
|
||
id: true,
|
||
name: true,
|
||
status: true,
|
||
},
|
||
orderBy: { updatedAt: 'desc' },
|
||
})
|
||
: []
|
||
|
||
// 生成所有预制模板,只包含启用的
|
||
// 如果 enabledBuiltinTemplates 为空数组,表示全部启用
|
||
const builtinTemplates = BUILTIN_TEMPLATE_KEYS
|
||
.filter(key => enabledBuiltinTemplates.length === 0 || enabledBuiltinTemplates.includes(key))
|
||
.map(key => {
|
||
const template = createBuiltinTemplate(key)
|
||
return {
|
||
id: template.id,
|
||
name: template.name,
|
||
isBuiltin: true,
|
||
}
|
||
})
|
||
|
||
if (!customTemplatesAllowed) {
|
||
return NextResponse.json(builtinTemplates)
|
||
}
|
||
|
||
const projected = await projectPublicTemplateOptionsWithPaidCore({
|
||
builtinTemplates,
|
||
customTemplates,
|
||
})
|
||
|
||
if (!projected.valid) {
|
||
return NextResponse.json({
|
||
error: projected.error || '付费增强包无法生成模板列表',
|
||
errorCode: projected.errorCode || 'TEMPLATE_PUBLIC_OPTIONS_PROJECT_FAILED',
|
||
details: projected.details,
|
||
}, { status: 503 })
|
||
}
|
||
|
||
return NextResponse.json(projected.templates)
|
||
} catch (error) {
|
||
console.error('Error fetching templates:', error)
|
||
return NextResponse.json({ error: '获取模板列表失败' }, { status: 500 })
|
||
}
|
||
}
|
||
|