From 06d38db279d1115fb0a0c14ae8a418eef8030973 Mon Sep 17 00:00:00 2001 From: Askar Yusupov Date: Mon, 5 Jun 2023 19:30:55 +0500 Subject: [PATCH 1/2] refactor(sse.js): refactor filterUser function to createFilter and add support for filtering shared collections by user id. --- middlewares/sse.js | 46 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/middlewares/sse.js b/middlewares/sse.js index a54bbb2..e39083f 100644 --- a/middlewares/sse.js +++ b/middlewares/sse.js @@ -1,17 +1,51 @@ 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; + return { + user({ session, user }) { + userId = session?.passport?.user || user?.id; + return filterByUserId(userId) || filterSharedCollections(userId); + }, + data: { + toJSON() { + return newData; + }, + }, + }; } - 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); }); } }; From 6856d949264808baa9f29bc2b4d1f658ae4175de Mon Sep 17 00:00:00 2001 From: Askar Yusupov Date: Mon, 12 Jun 2023 11:26:53 +0500 Subject: [PATCH 2/2] fix: replace toJSON to hackFn --- middlewares/sse.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/middlewares/sse.js b/middlewares/sse.js index e39083f..288e5e9 100644 --- a/middlewares/sse.js +++ b/middlewares/sse.js @@ -1,3 +1,4 @@ +const { stringify } = require('../_helpers'); const { hasAuthBearerHeader } = require('./apiToken'); module.exports = function (req, res, next) { @@ -26,16 +27,15 @@ module.exports = function (req, res, next) { } let userId; + const hackFn = () => {}; + hackFn.toString = () => stringify(newData); + return { user({ session, user }) { userId = session?.passport?.user || user?.id; return filterByUserId(userId) || filterSharedCollections(userId); }, - data: { - toJSON() { - return newData; - }, - }, + data: hackFn, }; }