任何想法如何实现所有路由可以使用的交易中间件?

问题描述 投票:0回答:1
这是我拥有的代码。

import mongoose from 'mongoose'; const session = await mongoose.startSession(); session.startTransaction(); export default async function transactionMiddleware(req, res, next) { try { await session.withTransaction(async () => { await next(); }); } catch (error) { await session.abortTransaction(); session.endSession(); return res.status(500).json({message: 'Something went wrong.'}); } await session.commitTransaction(); session.endSession(); };

这就是我在app.js文件中使用的方式。
我的问题是,当我导入此中间件时,它不会编译。我希望编译。

import transactionMiddleware from './src/middlewares/transactionMiddleware.js'; 像这样崩溃了

如果您的目的是创建可重复使用的代码来处理您的交易,则可能应该使用包装器函数。
以将其作为参数以参数执行的代码的函数:

const transactionWrapper = (callback) => { const session = await mongoose.startSession(); try { await session.withTransaction(async () => { await callback(); }); await session.commitTransaction(); session.endSession(); } catch (err) { await session.abortTransaction(); session.endSession(); throw err; } } 示例用法:

node.js mongodb express mongoose
1个回答
0
投票

如果有帮助,我这样做了:

import { Request, Response, NextFunction } from 'express' import mongoose from 'mongoose' /** * Middleware to manage MongoDB sessions within each request lifecycle. * This middleware initializes a MongoDB session and attaches it to the `req` object as `req.session`. * It ensures the session is closed after the response is sent to the client by listening to the `finish` event of the response object. * * @param {Request} req - The Express request object, augmented with the session object. * @param {Response} res - The Express response object, used to listen for the `finish` event to close the session. * @param {NextFunction} next - The callback function to continue processing the middleware stack. * * Usage: * The session is accessible via `req.session` in subsequent middleware and route handlers. * * Example: * app.use(sessionMiddleware) */ export async function sessionMiddleware(req: Request, res: Response, next: NextFunction) { const session = await mongoose.startSession() req.session = session try { await req.session.startTransaction() res.on('finish', async () => { if (res.statusCode >= 200 && res.statusCode < 300) { await req.session.commitTransaction() } else { await req.session.abortTransaction() } await req.session.endSession() }) next() } catch (error) { await req.session.abortTransaction() await req.session.endSession() next(error) } } export default sessionMiddleware
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.