Skip to content

Commit

Permalink
Prevent duplicate category saving (checking case insensitively).
Browse files Browse the repository at this point in the history
  • Loading branch information
miezis committed Jul 23, 2016
1 parent dc76bb6 commit 742873e
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion routes/categories.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ router.post('/', function (req, res) {
name: req.body.name
};

_checkForDupes(categories, newCategory);

categories.push(newCategory);

jf.writeFileSync(config.categories, categories);
Expand Down Expand Up @@ -61,6 +63,8 @@ router.put('/:id', function(req, res) {
name: req.body.name
};

_checkForDupes(categories, modifiedCategory);

newCategoryPath = path.join(config.database, modifiedCategory.name + config.extension);

categories.splice(categoryIndex, 1, modifiedCategory);
Expand All @@ -84,10 +88,24 @@ router.delete('/:id', function(req, res) {
return;
}

var categoryToDeletePath = path.join(config.database, category.name + config.extension);

fs.unlinkSync(categoryToDeletePath);

categories.splice(categoryIndex, 1);

jf.writeFileSync(config.categories, categories);
res.json(category);
});

module.exports = router;
function _checkForDupes(categories, category) {
var nameLower = _.toLower(category.name);

var containsDupe = _.some(categories, function (cat) { return _.toLower(cat.name) === nameLower});

if (containsDupe) {
throw new Error('Category with same name already exists!');
}
};

module.exports = router;

0 comments on commit 742873e

Please sign in to comment.