Skip to content

Commit

Permalink
Replace Fawn and use native transaction mongodb
Browse files Browse the repository at this point in the history
  • Loading branch information
bisu committed Aug 8, 2020
1 parent 324e31f commit a1735bf
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 143 deletions.
3 changes: 2 additions & 1 deletion config/custom-environment-variables.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"jwtPrivateKey": "vidly_jwtPrivateKey"
"jwtPrivateKey": "vidly_jwtPrivateKey",
"db": "vidly_db"
}
124 changes: 0 additions & 124 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"cors": "^2.8.5",
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"fawn": "^2.1.5",
"joi": "^17.2.0",
"joi-objectid": "^3.0.1",
"jsonwebtoken": "^8.5.1",
Expand Down
39 changes: 22 additions & 17 deletions routes/rentals.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@ const { Movie } = require("../models/movie");
const { Customer } = require("../models/customer");
const auth = require("../middleware/auth");
const mongoose = require("mongoose");
const Fawn = require("fawn");
const express = require("express");
const router = express.Router();

Fawn.init(mongoose);

router.get("/", auth, async (req, res) => {
const rentals = await Rental.find()
.select("-__v")
Expand Down Expand Up @@ -42,21 +39,29 @@ router.post("/", auth, async (req, res) => {
}
});

const session = await mongoose.startSession();

session.startTransaction();

try {
new Fawn.Task()
.save("rentals", rental)
.update(
"movies",
{ _id: movie._id },
{
$inc: { numberInStock: -1 }
}
)
.run();

res.send(rental);
} catch (ex) {
res.status(500).send("Something failed.");
await rental.save({ session });

await Movie.update(
{ _id: rental.movie._id },
{
$inc: { numberInStock: -1 }
},
{ session }
);

await session.commitTransaction();
res.send(rental)
} catch (error) {
await session.abortTransaction();

throw new Error(error);
} finally {
session.endSession();
}
});

Expand Down

0 comments on commit a1735bf

Please sign in to comment.