我使用打字稿。我想实现一个基于会话的身份验证系统。所以,我决定使用 fastify/session。 Prisma 用于存储会话。我的问题是,当我请求“/”路径(您可以在下面看到)时,它不会返回任何内容。我的邮递员只显示“正在发送请求...”并且没有任何返回。但数据库创建会话。在控制台中,我可以看到 sessionId (我在控制台中打印的)及其与数据库中的 sessionId 的匹配。我能做什么来解决这个问题?
我的index.ts文件,我实现了fastify和sessionStore:
import Fastify, { FastifyReply, FastifyRequest } from "fastify";
import fastifyCookie from "@fastify/cookie";
import fastifySession from "@fastify/session";
import { db } from "./libs/db";
const fastify = Fastify();
const PORT = Number(process.env.PORT) || 3000;
fastify.register(fastifyCookie);
fastify.register(fastifySession, {
store: {
set: async (sid: string, session: object) => {
await db.session.upsert({
where: { sid },
update: { session: JSON.stringify(session) },
create: { sid, session: JSON.stringify(session) },
});
},
get: async (sid: string) => {
try {
const storedSession = await db.session.findUnique({ where: { sid } });
return storedSession ? JSON.parse(storedSession.session) : null;
} catch (error) {
return null;
}
},
destroy: async (sid: string) => {
await db.session.delete({ where: { sid } });
},
},
cookieName: "sid",
secret: "supersecretkeysupersecretkeysupersecretkeysupersecretkey",
cookie: {
maxAge: 1000 * 60 * 60,
secure: process.env.NODE_ENV === "production",
},
});
fastify.get("/", (req: FastifyRequest, res: FastifyReply) => {
console.log(req.session.sessionId);
return { success: "Test sucess!" };
});
try {
fastify.listen({ port: PORT });
console.log(`Server is listening port ${PORT}`);
} catch (error) {
fastify.log.error(error);
process.exit(1);
}
我的 schema.prisma 文件:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model Session {
sid String @id @default(uuid())
session String
}
引起我注意的是,在index.d.ts文件中,fastify/session的源代码中的get、set和destory方法的声明是这样的:
set(
sessionId: string,
session: Fastify.Session,
callback: Callback
): void;
get(
sessionId: string,
callback: CallbackSession
): void;
destroy(sessionId: string, callback: Callback): void;
全部返回void,是这样吗?但是,如果 get 方法返回任何内容,我如何指示我从数据库或其他内容获取的会话是什么?或者我的 prisma.schema 文件中的会话模式,是这样吗?
仅仅返回是不够的:你应该打电话给
reply.send()
:
fastify.get("/", (req: FastifyRequest, res: FastifyReply) => {
console.log(req.session.sessionId);
res.send({ success: "Test success!" });
});
来源:文档。
如果您阅读文档,还有几个选项,例如使用
async/await
语法。