Luk*_*uke 5 api-design backend typescript next.js prisma
我在 Next.js API 路由中使用 Prisma (4.2.1) 进行基于光标的帖子分页。
当我将光标传递到 API 端点时,我在控制台中收到以下错误消息 (500):
TypeError: Cannot read properties of undefined (reading 'createdAt')
at getPost (webpack-internal:///(api)/./lib/api/post.ts:67:46)
error - TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of TypeError
Run Code Online (Sandbox Code Playgroud)
我正在使用 Postman 访问 API 端点。
当我从 API 路由中删除光标时,没有错误并且帖子按预期返回。
我尝试升级到最新的 Prisma 版本(4.2.1),在光标上使用 .toString() ,并将 AllPosts 接口更改为“any”,但我无法解决 TypeError。
如何修复此错误并使 Prisma 接受光标有效?
TypeError: Cannot read properties of undefined (reading 'createdAt')
at getPost (webpack-internal:///(api)/./lib/api/post.ts:67:46)
error - TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of TypeError
Run Code Online (Sandbox Code Playgroud)
import prisma from "@/lib/prisma";
import type { NextApiRequest, NextApiResponse } from "next";
import type { Post, Site } from ".prisma/client";
import type { Session } from "next-auth";
import { revalidate } from "@/lib/revalidate";
import type { WithSitePost } from "@/types";
interface AllPosts {
posts: Array<Post>;
site: Site | null;
}
export async function getPost(
req: NextApiRequest,
res: NextApiResponse,
session: Session
): Promise<void | NextApiResponse<AllPosts | (WithSitePost | null)>> {
const { postId, siteId, published, cursor } = req.query;
if (
Array.isArray(postId) ||
Array.isArray(siteId) ||
Array.isArray(published) ||
Array.isArray(cursor)
)
return res.status(400).end("Bad request. Query parameters are not valid.");
if (!session.user.id)
return res.status(500).end("Server failed to get session user ID");
try {
if (postId) {
const post = await prisma.post.findFirst({
where: {
id: postId,
site: {
user: {
id: session.user.id,
},
},
},
include: {
site: true,
},
});
return res.status(200).json(post);
}
const site = await prisma.site.findFirst({
where: {
id: siteId,
user: {
id: session.user.id,
},
},
});
const posts = !site
? []
: await prisma.post.findMany({
take: 10,
skip: cursor === undefined ? 0 : 1,
cursor: {
id: cursor,
},
where: {
site: {
id: siteId,
},
published: JSON.parse(published || "true"),
},
orderBy: {
createdAt: "desc",
},
});
const lastPostInResults = posts[9];
const nextCursor = lastPostInResults.createdAt;
return res.status(200).json({
posts,
site,
nextCursor,
});
} catch (error) {
console.error(error);
return res.status(500).end(error);
}
}
Run Code Online (Sandbox Code Playgroud)
通过添加@unique到 Post 模型、推送架构更改并使用prisma generate.
model Post {
createdAt DateTime @default(now())
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
521 次 |
| 最近记录: |