Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(sse.js): refactor filterUser function to createFilter and add support for filtering shared collections by user id. #91

Merged
merged 2 commits into from
Jun 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 40 additions & 6 deletions middlewares/sse.js
Original file line number Diff line number Diff line change
@@ -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);
});
}
};
Expand Down