const express = require('express'); const router = express.Router(); const tools = require('../tools/general'); const server_constants = require('../tools/server_constants'); const { authenticate } = require('../middleware/authenticate'); const { MyEvent } = require('../models/myevent'); const { ObjectID } = require('mongodb'); const sendemail = require('../sendemail'); const _ = require('lodash'); router.post('/', authenticate, (req, res) => { tools.mylog('INIZIO - MyEvent'); // tools.mylog('req.body', req.body); const myrec = _.pick(req.body, tools.allfieldMyEvent()); const id = myrec._id; const fieldtochange = _.pick(myrec, tools.allfieldMyEventChange()); tools.mylog('crea MyEvent'); const myevent = new MyEvent(myrec); const check = tools.checkUserOk(myevent.userId, req.user._id); if (check.exit) return check.ret; // Modify: return MyEvent.findOne({ id }) .then(trovato => { // console.log('trovato', trovato); if (trovato) { return myevent.findOneAndUpdate({ id }, { $set: fieldtochange }, { new: true, upsert: true }).then((recmyevent) => { // tools.mylog('myevent:', myevent); // tools.mylog('already exist'); sendNotif(res, myrec.idapp, req.user, recmyevent); res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id }); }); } else { // save to database a new record tools.mylog('save to database a new record'); myevent._id = new ObjectID(); return myevent.save().then((writeresult) => { let idobj = writeresult._id; myevent.findById(idobj) .then((recmyevent) => { sendNotif(res, myrec.idapp, req.user, recmyevent); res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id }); }); }); } }) }); router.delete('/:id/:notify/:idapp', authenticate, (req, res) => { console.log('DELETE myevent'); const id = req.params.id; const notify = req.params.notify; const idapp = req.params.idapp; myevent.findByIdAndRemove(id).then((recmyevent) => { if (!recmyevent) { return res.status(404).send(); } if (notify === '1') sendNotif(res, idapp, req.user, recmyevent); tools.mylog('DELETED ', recmyevent.descr, recmyevent._id); res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id }); }).catch((e) => { res.status(400).send(); }); }); router.get('/:userId/:idapp/:sall', authenticate, (req, res) => { const userId = req.params.userId; const idapp = req.params.idapp; const sall = req.params.sall; // var category = req.params.category; // tools.mylog('GET myeventS : ', req.params); if (!ObjectID.isValid(userId)) { return res.status(404).send(); } if (userId !== String(req.user._id)) { // I'm trying to write something not mine! return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); } // Extract all the todos of the userId only return MyEvent.findAllByUserIdAndIdApp(userId, idapp, sall).then((recevent) => { res.send({ recevent }); }).catch((e) => { console.log(e); res.status(400).send(e); }); }); module.exports = router;