synt_backend
Version:
Synt light-weight node backend service
113 lines (104 loc) • 3.14 kB
JavaScript
const express = require("express");
const router = express.Router();
const userHelper = require("./../helpers/user");
import * as ValidationHelper from "./../helpers/validations";
import db from "../mysql/models";
// routes
router.get("/", getNotifications);
router.get("/settings", getNotificationSettings);
router.post("/settings", postNotificationSettings);
router.post("/read", postReadNotification);
module.exports = router;
async function getNotifications(req, res) {
const { t } = req;
try {
let User = await userHelper.getAuthUser(req);
if (User) {
// verify vme and get vme
let VmeValidation = await ValidationHelper.validateVme(t, User.VMEId); //TODO: Validate user roles
if (!VmeValidation.success) {
return res.json(VmeValidation);
}
const { VME } = VmeValidation;
db.Notification.findAll({
where: { UserId: User.id, VMEId: VME.id },
})
.then((Notifications) => {
return res.json({ success: true, Notifications });
})
.catch((err) => console.log(err));
}
} catch (error) {
return res.json({ success: false, error });
}
}
async function postReadNotification(req, res) {
try {
let User = await userHelper.getAuthUser(req);
if (User) {
// TODO: save settings
const { id } = req.body;
db.Notification.update(
{ seen_at: new Date() },
{ where: { id, UserId: User.id } }
);
return res.json({
success: true,
});
}
} catch (error) {
return res.json({ success: false, error });
}
}
async function postNotificationSettings(req, res) {
try {
let User = await userHelper.getAuthUser(req);
if (User) {
// TODO: save settings
const { id, value } = req.body;
db.NotificationSettingUser.update(
{ value },
{ where: { NotificationSettingId: id, UserId: User.id } }
);
return res.json({
success: true,
});
}
} catch (error) {
return res.json({ success: false, error });
}
}
async function getNotificationSettings(req, res) {
const { t } = req;
try {
let User = await userHelper.getAuthUser(req);
if (User) {
// TODO: get settings
User.getNotificationSettings()
.then((NotificationSettings) => {
NotificationSettings = NotificationSettings.map((S) => {
S.setDataValue("value", S.NotificationSettingUser.value);
return S;
});
return res.json({
success: true,
NotificationSettings: [
{
title: t("api.notifications.titles.email", "Email"),
settings: NotificationSettings.filter(
(S) => S.type === "email"
),
},
{
title: t("api.notifications.titles.push", "Push"),
settings: NotificationSettings.filter((S) => S.type === "push"),
},
],
});
})
.catch((err) => console.log(err));
}
} catch (error) {
return res.json({ success: false, error });
}
}