mirror of
https://git.zhongyuan.online/ytke/tap.git
synced 2026-11-24 22:15:18 -08:00
25 lines
2.0 KiB
TypeScript
25 lines
2.0 KiB
TypeScript
import { readFile } from 'node:fs/promises';
|
|||
|
|
import { join } from 'node:path';
|
||
|
|
import { getCurrentUser } from '@/lib/server/auth';
|
||
|
|
import { findDocument } from '@/lib/documents';
|
||
|
|
export const runtime='nodejs';
|
||
|
|
export const dynamic='force-dynamic';
|
||
|
|
export async function GET(request:Request,{params}:{params:Promise<{name:string}>}) {
|
||
|
|
const user=await getCurrentUser();
|
||
|
|
if(!user)return Response.json({error:'请先登录。'},{status:401,headers:{'Cache-Control':'no-store'}});
|
||
|
|
if(user.mustChangePassword)return Response.json({error:'请先修改初始密码。'},{status:403,headers:{'Cache-Control':'no-store'}});
|
||
|
|
const {name}=await params;const document=findDocument(name);
|
||
|
|
if(!document)return Response.json({error:'找不到该文档。'},{status:404});
|
||
|
|
const format=new URL(request.url).searchParams.get('format')||'markdown';
|
||
|
|
if(!['json','markdown','docx'].includes(format))return Response.json({error:'不支持的文档格式。'},{status:400});
|
||
|
|
try{
|
||
|
|
if(format==='docx'){
|
||
|
|
const filename=document.filename.replace(/\.md$/,'.docx');
|
||
|
|
const data=await readFile(join(process.cwd(),'content','word',filename));
|
||
|
|
return new Response(new Uint8Array(data),{headers:{'Content-Type':'application/vnd.openxmlformats-officedocument.wordprocessingml.document','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
||
|
|
}
|
||
|
|
const content=await readFile(join(process.cwd(),'content','docs',document.filename),'utf8');
|
||
|
|
if(format==='json')return Response.json({id:document.id,title:document.title,content},{headers:{'Cache-Control':'private, no-store'}});
|
||
|
|
return new Response(content,{headers:{'Content-Type':'text/markdown; charset=utf-8','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(document.filename)}`,'Cache-Control':'private, no-store'}});
|
||
|
|
}catch(error){console.error('Document read failed',error);return Response.json({error:'文档暂时无法打开或下载,请稍后重试。'},{status:503,headers:{'Cache-Control':'no-store'}});}
|
||
|
|
}
|