const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 2,
host: '167.172.165.119',
user: 'simonlil',
password: 'Lilleeng92',
database: 'testTok',
debug: false
});
const Nd = require('../dao/notificationDao');
const notiDao = new Nd(pool);
/**
* @name Get all the users expoToken for one notificationtype
* @memberof module:Routes
* @route {GET} /notification/:notificationType
* @routeparam {String} [notificationType] Wanted notification type.
* @return {object} JSON-object containing all expoTokens subscribing to the notificationType.
*/
router.get('/:notificationType', (req, res) => {
const { notificationType } = req.params;
console.log('Handling GET request to /notification/', notificationType);
notiDao.getAll(notificationType, (status, data) => {
res.status(status);
res.json(data);
});
});
/**
* Get the users notificationsettings.
* If hes not in the database. The server will insert him.
* @name Get users notificationSettings.
* @memberof module:Routes
* @route {PUT} /notification/settings
* @bodyparam {String} [expoToken] The users unique device expoToken.
* @bodyparam {String} [associationType] The users associationType e.g "BANK"
*/
router.put('/settings', (req, res) => {
console.log('Handling PUT request to /notification/settings');
const { expoToken, associationType } = req.body;
let result;
function sendData() {
notiDao.getSettings(req.body, (status, data) => {
res.status(status);
res.json(data);
});
}
function insertCallback() {
console.log('Inserting to table...');
}
function insertToTable(status, data) {
data.forEach(element => {
console.log(element);
notiDao.insert(
{
expoToken: expoToken,
notificationType: element.notificationType,
associationType: associationType
},
insertCallback
);
});
sendData();
}
async function callback(status, data) {
result = await data[0].exist;
if (result) {
sendData();
} else {
notiDao.getNotificationTypes(associationType, insertToTable);
}
}
notiDao.checkExist(req.body, callback);
});
/**
* Used to change notificationsettings.
* @name Update users notificationsettings.
* @memberof module:Routes
* @route {PUT} /notification
* @bodyparam {newValue} [boolean] Subscribe or not to the notificationType.
* @bodyparam {expoToken} [String] The users unique device expoToken.
* @bodyparam {notificationType} [String] Selected notification type to change.
* @bodyparam {associationType} [String] Users associationType e.g "BANK".
*/
router.put('/', (req, res) => {
console.log('Handling PUT request on /notification');
const { newValue, expoToken, notificationType, associationType } = req.body;
notiDao.update(
{
newValue: newValue,
expoToken: expoToken,
notificationType: notificationType,
associationType: associationType
},
(status, data) => {
res.status(status);
res.json(data);
}
);
});
module.exports = router;