【发布时间】:2021-10-08 23:06:00
【问题描述】:
我正在构建一个使用 fastify、Prisma 和 Postgres 的 nodejs api。我有使用 fastify-cookies 和 fastify-session 的 API,我可以很好地获取 cookie,但我需要能够将会话 cookie 存储在数据库中。我看到了tutorial 这样做,但它没有 prisma,所以我不知道如何将 fastify-session 连接到 Prisma 数据库池。
我使用 prisma 客户端连接到数据库以在我的路由中进行正常调用,const data = await prisma.model.create({});
server.js
const fastify = require('fastify')({ logger: true });
const PORT = process.env.PORT || 3000;
// Session state
fastify.register(require('./sessions'));
// Register all our routes here.
...
// Startup code for the fastify server.
const start = async () => {
try {
await fastify.listen(PORT, '0.0.0.0');
} catch (error) {
fastify.log.error(error);
process.exit(1);
}
};
// Start the fastify server.
start();
sessions.js
const cookie = require('fastify-cookie');
const session = require('fastify-session');
const fp = require('fastify-plugin');
/**
* @param {import('fastify').FastifyInstance} fastify
*/
const plugin = async (fastify) => {
// All plugin data here is global to fastify.
fastify.register(cookie);
fastify.register(session, {
secret: process.env.SESSION_SECRET,
store: new SessionStore({
tableName: 'UserSession',
pool: ???, <--------------------------------- how to connect?
}),
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: false,
},
});
fastify.addHook('preHandler', (req, reply, next) => {
req.session.user = {};
next();
});
};
module.exports = fp(plugin);
【问题讨论】:
标签: javascript node.js postgresql prisma fastify