我正在尝试将以下API从Next.js转换为Astro.build:
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "lib/prisma";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
// @ts-ignore
const slug = req.query.slug.toString();
const contentType = req.body.contentType;
if (req.method === "POST") {
const newOrUpdatedViews = await prisma.view.upsert({
where: { slug },
create: {
slug,
contentType: contentType,
},
update: {
count: {
increment: 1,
},
},
});
return res.status(200).json({
total: newOrUpdatedViews.count.toString(),
});
}
if (req.method === "GET") {
const views = await prisma.view.findUnique({
where: {
slug,
},
});
// @ts-ignore
return res.status(200).json({ total: views.count.toString() });
}
} catch (e) {
// @ts-ignore
return res.status(500).json({ message: e.message });
}
}
我试着在https://docs.astro.build/en/core-concepts/endpoints/的帮助下编辑它,但最终没有结果。到目前为止,API看起来像这样,但我不知道从哪里得到的响应:
import type {APIRoute} from "astro"
export const get: APIRoute = async function get({params, request}) {
try {
const slug = request.query.slug.toString()
const contentType = request.body.contentType
if (request.method === "POST") {
const newOrUpdatedViews = await prisma.view.upsert({
where: {slug},
create: {
slug,
contentType: contentType,
},
update: {
count: {
increment: 1,
},
},
})
return res.status(200).json({
total: newOrUpdatedViews.count.toString(),
})
}
if (request.method === "GET") {
const views = await prisma.view.findUnique({
where: {
slug,
},
})
// @ts-ignore
return res.status(200).json({total: views.count.toString()})
}
} catch (e) {
// @ts-ignore
return res.status(500).json({message: e.message})
}
}
VS代码告诉我,查询不存在于以下行中:
const slug = request.query.slug.toString()
这一行的contentType也是如此:
const contentType = request.body.contentType
Astro的API会是什么样子?
1条答案
按热度按时间6kkfgxo01#
您将为每个方法导出一个不同的处理程序。您已经为
GET
方法导出了一个处理程序。对POST
也执行相同的操作。您可以在文档站点的Endpoints页面上阅读更多内容。