-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
63 lines (56 loc) · 1.74 KB
/
index.ts
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
import { Hono } from "hono";
import { readFile, readdir } from "fs/promises";
import { join } from "path";
import matter from "gray-matter";
const app = new Hono();
const recipesDirectory = join(import.meta.dir, "recipes");
function parseCodeBlocks(mdxContent: string) {
const codeBlockRegex = /```(\w*)([\s\S]*?)```/g;
const blocks = [];
let match;
while ((match = codeBlockRegex.exec(mdxContent)) !== null) {
const language = match[1];
const code = match[2].trim();
blocks.push({ language, code });
}
return blocks;
}
interface FileInfo {
name: string;
path: string;
type: string;
}
app.get("/registry/:id", async (c) => {
const id = c.req.param("id");
try {
const filePath = join(recipesDirectory, `${id}.mdx`);
const content = await readFile(filePath, "utf-8");
const { data, content: mdxContent } = matter(content);
const codeBlocks = parseCodeBlocks(mdxContent);
return c.json({
recipeId: id,
codeBlocks,
dependencies: data.dependencies || {},
files: data.files as FileInfo[],
});
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
return c.json({ error: "Recipe not found" }, 404);
}
console.error(`Error reading recipe ${id}:`, error);
return c.json({ error: "Internal server error" }, 500);
}
});
app.get("/recipes", async (c) => {
try {
const files = await readdir(recipesDirectory);
const recipes = files
.filter((file) => file.endsWith(".mdx"))
.map((file) => file.replace(".mdx", ""));
return c.json(recipes);
} catch (error) {
console.error("Error reading recipes directory:", error);
return c.json({ error: "Internal server error" }, 500);
}
});
export default app;