Files
guanwang/scripts/seed-mock-content.mjs

32 lines
1.9 KiB
JavaScript

import { readFile } from 'node:fs/promises'
const baseUrl = (process.env.SITE_URL || 'http://localhost:3000').replace(/\/$/, '')
const username = process.env.ADMIN_USERNAME || 'admin'
const password = process.env.ADMIN_PASSWORD
if (!password) throw new Error('请通过 ADMIN_PASSWORD 环境变量提供后台密码')
const loginResponse = await fetch(`${baseUrl}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
})
if (!loginResponse.ok) throw new Error(`后台登录失败: ${loginResponse.status}`)
const cookie = loginResponse.headers.get('set-cookie')?.split(';')[0]
if (!cookie) throw new Error('后台登录未返回会话 Cookie')
const headers = { Cookie: cookie }
const currentResponse = await fetch(`${baseUrl}/api/admin/site`, { headers })
if (!currentResponse.ok) throw new Error(`读取后台草稿失败: ${currentResponse.status}`)
const current = (await currentResponse.json()).data
const mock = JSON.parse(await readFile(new URL('../content/演示数据/一期官网演示数据.json', import.meta.url), 'utf8'))
const document = { ...current, ...mock, hero: { ...current.hero, titleLine1: '身心疗愈', titleLine2: '科技赋能', subtitle: '用科技与专业,陪伴每一次心灵的成长', cta: '了解慧遇书院' } }
const saveResponse = await fetch(`${baseUrl}/api/admin/site`, {
method: 'PUT', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(document),
})
if (!saveResponse.ok) throw new Error(`保存演示草稿失败: ${saveResponse.status} ${await saveResponse.text()}`)
const publishResponse = await fetch(`${baseUrl}/api/admin/site/publish`, { method: 'POST', headers })
if (!publishResponse.ok) throw new Error(`发布演示数据失败: ${publishResponse.status} ${await publishResponse.text()}`)
const result = await publishResponse.json()
console.log(`演示数据已写入后台并发布为 V${result.version}`)