diff --git a/middlewares/sse.js b/middlewares/sse.js index a54bbb2..288e5e9 100644 --- a/middlewares/sse.js +++ b/middlewares/sse.js @@ -1,17 +1,51 @@ +const { stringify } = require('../_helpers'); const { hasAuthBearerHeader } = require('./apiToken'); module.exports = function (req, res, next) { - function filterUser({ session, user }) { - const userId = session?.passport?.user || user?.id; - return req.user && req.user.id === userId; + function createFilter(data, event, _id) { + let newData = null; + function filterByUserId(userId) { + newData = { ...data }; + return req.user && req.user.id === userId; + } + + function filterSharedCollections(userId) { + newData = null; + if (event !== 'collections') { + return false; + } + + const sharedCollections = data.data?.filter(({ visibility, users }) => { + return visibility === 'shared' && users?.includes(userId); + }); + + if (sharedCollections.length) { + newData = { ...data, data: sharedCollections, total: sharedCollections.length }; + return true; + } + return false; + } + + let userId; + const hackFn = () => {}; + hackFn.toString = () => stringify(newData); + + return { + user({ session, user }) { + userId = session?.passport?.user || user?.id; + return filterByUserId(userId) || filterSharedCollections(userId); + }, + data: hackFn, + }; } - res.sse.sendTo = function (...args) { + res.sse.sendTo = function (data, event, id) { + const filters = createFilter(data, event, id); if (hasAuthBearerHeader(req)) { - this.send(filterUser, ...args); + this.send(filters.user, filters.data, event, id); } else { req.session.save(() => { - this.send(filterUser, ...args); + this.send(filters.user, filters.data, event, id); }); } };