Files
habitica/website/common/script/ops/sell.js
Matteo Pagliazzi 0b8ce63c76 WIP: Improve User model performances (#10832)
* wip: define items as mixed objects

* add default owned gear

* mark modified

* more mark modified

* more mark modified

* more mark modified

* more mark modified

* fix common tests

* fix common tests

* update mongoose

* add itemsUtils

* use new util function in hall controller

* add tests for items utils

* update website/server to mark all items as modified

* start updating common code

* update login incentives

* update unlock

* remove changes to package-lock.json

* remove changes to package.json
2019-04-01 19:24:18 +02:00

55 lines
1.4 KiB
JavaScript

import content from '../content/index';
import i18n from '../i18n';
import get from 'lodash/get';
import pick from 'lodash/pick';
import splitWhitespace from '../libs/splitWhitespace';
import {
NotFound,
NotAuthorized,
BadRequest,
} from '../libs/errors';
// @TODO: 'special' type throws NotAuthorized error
const ACCEPTEDTYPES = ['eggs', 'hatchingPotions', 'food'];
module.exports = function sell (user, req = {}) {
let key = get(req.params, 'key');
let type = get(req.params, 'type');
let amount = get(req.query, 'amount', 1);
if (amount < 0) {
throw new BadRequest(i18n.t('positiveAmountRequired', req.language));
}
if (!type) {
throw new BadRequest(i18n.t('typeRequired', req.language));
}
if (!key) {
throw new BadRequest(i18n.t('missingKeyParam', req.language));
}
if (ACCEPTEDTYPES.indexOf(type) === -1) {
throw new NotAuthorized(i18n.t('typeNotSellable', {acceptedTypes: ACCEPTEDTYPES.join(', ')}, req.language));
}
if (!user.items[type][key]) {
throw new NotFound(i18n.t('userItemsKeyNotFound', {type}, req.language));
}
let currentAmount = user.items[type][key];
if (amount > currentAmount) {
throw new NotFound(i18n.t('userItemsNotEnough', {type}, req.language));
}
user.items[type][key] -= amount;
if (user.markModified) user.markModified(`items.${type}`);
user.stats.gp += content[type][key].value * amount;
return [
pick(user, splitWhitespace('stats items')),
];
};