api routes with non-blocking method

This commit is contained in:
Cypro Freelance 2024-07-21 01:07:40 +05:30
parent 828d9bd7b0
commit 54ac1d08d6
2 changed files with 85 additions and 72 deletions

View file

@ -1,63 +1,65 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import fs from "fs"; import { promises as fs } from "fs";
import path from "path"; import path from "path";
import matter from "gray-matter"; import matter from "gray-matter";
// Define the path to the changelogs directory const changelogsDir = path.resolve(process.cwd(), "data/pages");
const pagesDir = path.join(process.cwd(), "data", "pages");
export async function GET( async function getMDXFiles(dir: string): Promise<string[]> {
request: NextRequest, const files = await fs.readdir(dir);
{ params }: { params: { slug: string } } return files.filter((file) => file.endsWith(".mdx"));
) { }
const { slug } = params;
const filePath = path.join(pagesDir, `${slug}.mdx`);
export async function GET() {
try { try {
const content = fs.readFileSync(filePath, "utf8"); const mdxFiles = await getMDXFiles(changelogsDir);
// Use gray-matter to parse the front matter and content const pages = await Promise.all(
mdxFiles.map(async (file) => {
const filePath = path.join(changelogsDir, file);
const content = await fs.readFile(filePath, "utf-8");
const { data, content: mdxContent } = matter(content); const { data, content: mdxContent } = matter(content);
return NextResponse.json({ title: data.title, content: mdxContent }); const slug = path.basename(file, path.extname(file));
return {
metadata: data,
slug,
content: mdxContent,
};
})
);
return NextResponse.json(pages, { status: 200 });
} catch (error) { } catch (error) {
console.error("Failed to load page:", error); console.error("Failed to fetch pages:", error);
return NextResponse.json({ error: "Page not found" }, { status: 404 });
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: { slug: string } }
) {
const { slug } = params;
const filePath = path.join(pagesDir, `${slug}.mdx`);
const { title, content } = await request.json();
try {
fs.writeFileSync(filePath, `---\ntitle: ${title}\n---\n${content}`);
return NextResponse.json({ title, slug, content });
} catch (error) {
console.error("Failed to update page:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Failed to update page" }, { error: "Failed to fetch pages" },
{ status: 500 } { status: 500 }
); );
} }
} }
export async function DELETE( export async function POST(request: NextRequest) {
request: NextRequest, const { title } = await request.json();
{ params }: { params: { slug: string } } const slug = title.toLowerCase().replace(/\s+/g, "-");
) { const filePath = path.join(changelogsDir, `${slug}.mdx`);
const { slug } = params;
const filePath = path.join(pagesDir, `${slug}.mdx`);
try { try {
fs.unlinkSync(filePath); if (
return NextResponse.json({}, { status: 204 }); await fs
} catch (error) { .stat(filePath)
console.error("Failed to delete page:", error); .then(() => true)
.catch(() => false)
) {
return NextResponse.json( return NextResponse.json(
{ error: "Failed to delete page" }, { error: "Page already exists" },
{ status: 400 }
);
}
await fs.writeFile(filePath, `---\ntitle: ${title}\n---\n`);
return NextResponse.json({ title, slug }, { status: 201 });
} catch (error) {
console.error("Failed to create page:", error);
return NextResponse.json(
{ error: "Failed to create page" },
{ status: 500 } { status: 500 }
); );
} }

View file

@ -1,52 +1,63 @@
import fs from "fs";
import path from "path";
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { promises as fs } from "fs";
import path from "path";
import matter from "gray-matter"; import matter from "gray-matter";
const changelogsDir = path.resolve(process.cwd(), "data/pages"); // Define the path to the changelogs directory
const pagesDir = path.join(process.cwd(), "data", "pages");
function getMDXFiles(dir: string): string[] { export async function GET(
return fs.readdirSync(dir).filter((file) => file.endsWith(".mdx")); request: NextRequest,
} { params }: { params: { slug: string } }
) {
const { slug } = params;
const filePath = path.join(pagesDir, `${slug}.mdx`);
export async function GET() {
try { try {
const mdxFiles = getMDXFiles(changelogsDir); const content = await fs.readFile(filePath, "utf8");
const pages = mdxFiles.map((file) => { // Use gray-matter to parse the front matter and content
const filePath = path.join(changelogsDir, file);
const content = fs.readFileSync(filePath, "utf-8");
const { data, content: mdxContent } = matter(content); const { data, content: mdxContent } = matter(content);
const slug = path.basename(file, path.extname(file)); return NextResponse.json({ title: data.title, content: mdxContent });
return {
metadata: data,
slug,
content: mdxContent,
};
});
return NextResponse.json(pages, { status: 200 });
} catch (error) { } catch (error) {
return NextResponse.json( console.error("Failed to load page:", error);
{ error: "Failed to fetch pages" }, return NextResponse.json({ error: "Page not found" }, { status: 404 });
{ status: 500 }
);
} }
} }
export async function POST(request: NextRequest) { export async function PUT(
const { title } = await request.json(); request: NextRequest,
const slug = title.toLowerCase().replace(/\s+/g, "-"); { params }: { params: { slug: string } }
const filePath = path.join(changelogsDir, `${slug}.mdx`); ) {
const { slug } = params;
if (fs.existsSync(filePath)) { const filePath = path.join(pagesDir, `${slug}.mdx`);
return NextResponse.json({ error: "Page already exists" }, { status: 400 }); const { title, content } = await request.json();
}
try { try {
fs.writeFileSync(filePath, `---\ntitle: ${title}\n---\n`); await fs.writeFile(filePath, `---\ntitle: ${title}\n---\n${content}`);
return NextResponse.json({ title, slug }, { status: 201 }); return NextResponse.json({ title, slug, content });
} catch (error) { } catch (error) {
console.error("Failed to update page:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Failed to create page" }, { error: "Failed to update page" },
{ status: 500 }
);
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: { slug: string } }
) {
const { slug } = params;
const filePath = path.join(pagesDir, `${slug}.mdx`);
try {
await fs.unlink(filePath);
return NextResponse.json({}, { status: 204 });
} catch (error) {
console.error("Failed to delete page:", error);
return NextResponse.json(
{ error: "Failed to delete page" },
{ status: 500 } { status: 500 }
); );
} }