backend: route save / restore

This commit is contained in:
muerwre 2018-11-30 13:49:03 +07:00
parent 032821329b
commit d932fcb287
17 changed files with 163 additions and 43 deletions

View file

@ -0,0 +1,43 @@
const { User, Route } = require('../../models');
const { parseRoute, parseStickers, parseString, parseNumber } = require('../../utils/parse');
module.exports = async (req, res) => {
const { body, body: { id, token, force } } = req;
const owner = await User.findOne({ _id: id, token });
if (!owner) return res.send({ success: false, reason: 'Unauthorized' });
const title = parseString(body.title, 32);
const address = parseString(body.address, 32);
const route = parseRoute(body.route);
const stickers = parseStickers(body.stickers);
const logo = parseString(body.logo, 16);
const distance = parseNumber(body.distance, 0, 1000);
if ((!route || route.length <= 0) && (!stickers || stickers.length <= 0)) {
return res.send({ success: false, mode: 'empty' });
}
const exists = await Route.findOne({ _id: address }).populate('owner');
if (exists && exists.owner._id !== id) return res.send({ success: false, mode: 'exists' });
if (exists && !force) return res.send({ success: false, mode: 'overwriting' });
if (exists) {
exists.set({ title, route, stickers, logo, distance }).save();
return res.send({
success: true, title, address, route, stickers, mode: 'overwrited'
});
}
await Route.create({
_id: address, title, route, stickers, owner, logo, distance,
});
return res.send({
success: true, title, address, route, stickers
});
};