-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathroute.ts
More file actions
72 lines (62 loc) · 2.15 KB
/
route.ts
File metadata and controls
72 lines (62 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { NextRequest, NextResponse } from "next/server";
import { readFile, readdir, stat } from "fs/promises";
import { join, extname } from "path";
import { logger } from "@/lib/logger";
import { parseQuery } from "@/lib/validation";
import { filesQuerySchema } from "@/lib/validation/schemas/files";
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const parsed = parseQuery(searchParams, filesQuerySchema);
if (!parsed.success) return parsed.response;
const file = parsed.data.file ?? null;
const listDir = parsed.data.list ?? null;
const dirPath = parsed.data.path ?? "";
const baseDir = join(process.cwd(), "documents");
if (listDir === "true") {
const targetDir = join(baseDir, dirPath);
const entries = await readdir(targetDir, { withFileTypes: true });
const items = await Promise.all(
entries.map(async (entry) => {
const fullPath = join(targetDir, entry.name);
const stats = await stat(fullPath);
return {
name: entry.name,
type: entry.isDirectory() ? "directory" : "file",
size: stats.size,
modified: stats.mtime.toISOString(),
};
})
);
return NextResponse.json({
path: dirPath,
items,
});
}
if (!file) {
return NextResponse.json(
{ error: "File parameter is required" },
{ status: 400 }
);
}
const filePath = join(baseDir, file);
const extension = extname(file).toLowerCase();
if (extension === ".pdf") {
const content = await readFile(filePath);
return new NextResponse(content, {
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": `inline; filename="${file.split("/").pop()}"`,
},
});
}
const content = await readFile(filePath, "utf-8");
return NextResponse.json({
filename: file,
content,
});
} catch (error) {
logger.error({ err: error, route: "/api/files" }, "Error reading file");
return NextResponse.json({ error: "Failed to read file" }, { status: 500 });
}
}