Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module.exports.tradeItems = (req, res) => {
- const config = require('../config');
- const points = config.app.inventoryPoints;
- let idBuyer = req.params.id;
- let wanted = req.body.wanted;
- let recipient = req.body.recipient;
- let payment = req.body.payment;
- let wantedPoints = 0;
- let paymentPoints = 0;
- Object.keys(wanted).forEach((key) => {
- if (!points[key]) {
- //error
- return;
- }
- wantedPoints += wanted[key] * points[key];
- });
- Object.keys(payment).forEach((key) => {
- if (!points[key]) {
- //error
- }
- paymentPoints += payment[key] * points[key];
- });
- if (wantedPoints != paymentPoints) {
- res.status(412).send('ops');
- return;
- }
- let pBuyer = new Promise((resolve, reject) => {
- Survivor.findById(idBuyer, (err, survivor) => {
- if (err)
- return reject(err);
- return resolve(survivor);
- });
- });
- let pRecipient = new Promise((resolve, reject) => {
- Survivor.findById({
- _id: recipient.id,
- name: recipient.name
- }, (err, survivor) => {
- if (err)
- return reject(err);
- return resolve(survivor);
- });
- });
- Promise.all([pBuyer, pRecipient])
- .then((data) => {
- let survivorBuyer = data[0];
- let survivorRecipient = data[1];
- Object.keys(payment).forEach((key) => {
- if (payment[key] > survivorBuyer.inventory[key]) {
- //error
- return;
- }
- });
- Object.keys(wanted).forEach((key) => {
- if (wanted[key] > survivorRecipient.inventory[key]) {
- //error
- return;
- }
- });
- Object.keys(wanted).forEach((key) => {
- survivorBuyer.inventory[key] += wanted[key];
- survivorRecipient.inventory[key] -= wanted[key];
- });
- Object.keys(payment).forEach((key) => {
- survivorRecipient.inventory[key] += payment[key];
- survivorBuyer.inventory[key] -= payment[key];
- });
- survivorBuyer.save((err) => {
- survivorRecipient.save((err) => {
- res.status(200).send('ok');
- });
- });
- })
- .catch((data) => {
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement