Files
freeplanet_serverside/server/router/todos_router.js
Paolo Arena db2a460594 - add: createPushSubscription :
'Subscribed to FreePlanet.app!',
  'You can now receive Notification and Messages.'
2019-02-05 18:17:44 +01:00

118 lines
2.5 KiB
JavaScript

const express = require('express');
const router = express.Router();
const webpush = require('web-push');
var { authenticate } = require('../middleware/authenticate');
var { Todo } = require('../models/todo');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
const allfieldTodo = ['userId', 'pos', 'category', 'descr', 'priority', 'completed', 'created_at', 'modify_at',
'completed_at', 'expiring_at', 'enableExpiring', 'id_prev', 'id_next', 'progress', 'modified'];
const allfieldTodoWithId = ['_id', ...allfieldTodo];
router.post('/:id', authenticate, (req, res) => {
var body = _.pick(req.body, allfieldTodoWithId);
var todo = new Todo(body);
console.log('POST ', todo.descr);
todo.modified = false;
if (!todo.descr) {
console.log('RECORD NON VALIDO !?', req.body)
}
sendNotificationToUser('New Post', 'New Post added!', '/' + todo.category);
todo.save().then((doc) => {
res.send(doc);
}).catch((e) => {
console.log(e.message);
res.status(400).send(e);
});
});
router.patch('/:id', authenticate, (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, allfieldTodo);
if (!ObjectID.isValid(id)) {
console.log('ERROR: id not VALID', id);
return res.status(404).send();
}
Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
if (!todo) {
return res.status(404).send();
}
todo.modified = false
res.send({todo});
}).catch((e) => {
res.status(400).send();
})
});
function sendNotificationToUser(title, content, openUrl) {
// Create payload
const payload = JSON.stringify(
{
title,
content,
openUrl
}
);
subscriptioncfg = {};
// Pass object into sendNotification
webpush.sendNotification(subscriptioncfg, payload).catch(err => console.error(err));
}
router.get('/:userId', authenticate, (req, res) => {
var userId = req.params.userId;
console.log('GET : ', req.params);
// Extract all the todos of the userId only
Todo.findAllByUserId(userId).then((todos) => {
res.send({ todos });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
router.delete('/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Todo.findByIdAndRemove(id).then((todo) => {
if (!todo) {
return res.status(404).send();
}
res.send({todo});
}).catch((e) => {
res.status(400).send();
});
});
module.exports = router;