Created
June 25, 2021 10:12
-
-
Save richardscarrott/0567012a679d5110233e6f3dc5fdd304 to your computer and use it in GitHub Desktop.
MongoDB withTransaction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The docs for mongodb native driver sessions are pretty bare. The best example I can find is | |
// https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions | |
// but the code is generally not pretty; I think the following is likely the most suitable API: | |
// const doc = withTransaction(async session => { | |
// const doc = await users.updateOne({ _id: id }, { $set: { email } }, { returnOriginal: false, session }); | |
// await orders.updateMany({ email }, { $set: { userId: id } }, { session }); | |
// return doc; | |
// }); | |
const withTransaction = async <T>( | |
fn: (session: ClientSession) => Promise<T> | |
) => { | |
const session = mongoClient.startSession(); | |
try { | |
let result: T; | |
await session.withTransaction(async () => { | |
// https://jira.mongodb.org/browse/NODE-2014 | |
result = await fn(session); | |
}); | |
// @ts-ignore | |
return result; | |
} finally { | |
await session.endSession(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment