list.get.ts 1.15 KB
import { readdir, readFile, stat } from 'node:fs/promises'
import { join } from 'node:path'

export interface PromptItem {
  filename: string
  path: string
  content: string
  updatedAt: string
}

export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  const includeContent = query.content !== '0' && query.content !== 'false'

  const promptDir = join(process.cwd(), 'prompt')
  let files: string[] = []
  try {
    files = await readdir(promptDir)
  } catch {
    return { items: [] as PromptItem[] }
  }

  const items: PromptItem[] = []
  for (const f of files) {
    if (!f.endsWith('.md') || f === 'README.md') continue
    const filePath = join(promptDir, f)
    try {
      const st = await stat(filePath)
      const content = includeContent
        ? await readFile(filePath, 'utf-8')
        : ''
      items.push({
        filename: f,
        path: `prompt/${f}`,
        content,
        updatedAt: st.mtime.toISOString(),
      })
    } catch {
      // 跳过无法读取的文件
    }
  }

  // 按更新时间倒序
  items.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())

  return { items }
})