Files
freeplanet_serverside/server/router/todos_router.js
Paolo Arena d24b232a2d - fix: Date problems... (it was a bad "copy" function, the object date was not valid...)
- fix: error fetch on loading... (offline appeared)
2019-02-11 02:59:05 +01:00

228 lines
5.6 KiB
JavaScript

const express = require('express');
const router = express.Router();
const webpush = require('web-push');
const tools = require('../tools/general');
var server_constants = require('../tools/server_constants');
var { authenticate } = require('../middleware/authenticate');
var mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');
var { Todo } = require('../models/todo');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
router.post('/', authenticate, (req, res) => {
var body = _.pick(req.body, tools.allfieldTodoWithId());
tools.mylogshow('INPUT', body);
var todo = new Todo(body);
// todo.expiring_at = new Date(todo.expiring_at);
tools.mylogshow('TODO', todo);
tools.mylog('ID :', todo._id);
tools.mylog('userid', todo.userId, req.user._id);
if (!('descr' in req.body)){
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
}
if (String(todo.userId) !== String(req.user._id)) {
// I'm trying to write something not mine!
tools.mylog('todo.userId = ', todo.userId, 'req.user._id', req.user._id)
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
tools.mylog('TODO POST :', todo.descr, todo._id);
todo.modified = false;
if (!todo.descr) {
console.log('RECORD NON VALIDO !?', req.body)
}
sendNotificationToUser(todo.userId, 'New Todo', 'New Todo added!', '/' + todo.category, 'todo');
todo.save().then((writeresult) => {
let idobj = writeresult._id;
Todo.findById(idobj)
.then(record => {
tools.mylog('REC SAVED :', record.descr);
res.send({record});
})
}).catch((e) => {
console.log('ERRORE in TODO POST', e.message);
res.status(400).send(e);
});
});
function sendNotificationToUser(userId, title, content, openUrl, tag) {
const payload = {
title: title,
message: content,
url: openUrl,
tag,
// ttl: req.body.ttl,
// icon: req.body.icon,
// image: req.body.image,
// badge: req.body.badge,
// tag: req.body.tag
};
Subscription.find({userId: userId}, (err, subscriptions) => {
if (err) {
console.error(`Error occurred while getting subscriptions`);
res.status(500).json({
error: 'Technical error occurred'
});
} else {
let parallelSubscriptionCalls = subscriptions.map((subscription) => {
return new Promise((resolve, reject) => {
const pushSubscription = {
endpoint: subscription.endpoint,
keys: {
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth
}
};
const pushPayload = JSON.stringify(payload);
const pushOptions = {
vapidDetails: {
subject: process.env.URLBASE_APP1,
privateKey: process.env.PRIVATE_VAPI_KEY,
publicKey: process.env.PUBLIC_VAPI_KEY,
},
TTL: payload.ttl,
headers: {}
};
webpush.sendNotification(
pushSubscription,
pushPayload,
pushOptions
).then((value) => {
resolve({
status: true,
endpoint: subscription.endpoint,
data: value
});
}).catch((err) => {
reject({
status: false,
endpoint: subscription.endpoint,
data: err
});
});
}).catch(error => {
console.log('ERROR: sendNotificationToUser', error
)
});
});
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
// console.info(pushResults);
// });
// res.json({
// data: 'Push triggered'
// });
}
});
}
router.patch('/:id', authenticate, (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, tools.allfieldTodo());
tools.mylogshow('PATCH TODO: ', id)
if (!ObjectID.isValid(id)) {
tools.mylog('ERROR: id not VALID', id);
return res.status(404).send();
}
Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
tools.mylogshow(' TODO TO MODIFY: ', todo)
if (!todo) {
return res.status(404).send();
}
if (todo.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 });
}
todo.modified = false;
tools.mylog('PATCH ', todo.descr, todo._id);
res.send({todo});
}).catch((e) => {
res.status(400).send();
})
});
router.get('/:userId', authenticate, (req, res) => {
var userId = req.params.userId;
tools.mylog('GET : ', 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
Todo.findAllByUserId(userId).then((todos) => {
tools.mylog('todos', todos);
res.send({ todos: todos });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
router.delete('/:id', authenticate, (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();
}
tools.mylog('DELETED ', todo.descr, todo._id);
res.send({todo});
}).catch((e) => {
res.status(400).send();
});
});
module.exports = router;