【问题标题】:fastify and prisma with postgres session storage使用 postgres 会话存储进行 fastify 和 prisma
【发布时间】: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


    【解决方案1】:

    如果您想使用 Prisma 连接池,您必须创建一个类似于 connect-pg-simple 的会话存储库或修改代码库以接受 Prisma 连接。这绝对是一个不平凡的实现,如果没有特殊情况,我认为它没有多大意义。

    我建议创建一个新的pg.PoolpgPromise 实例并像您链接到的tutorial video 中显示的那样连接它。没有理由不能为同一个数据库打开两个单独的连接池(一个使用 Prisma,一个使用 pg.Pool)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 2022-01-02
      • 2019-05-10
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      相关资源
      最近更新 更多