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

Feat:lazy load discord groups page #2184

Closed
Show file tree
Hide file tree
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
18 changes: 15 additions & 3 deletions controllers/discordactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,20 @@
* @param res {Object} - Express response object
*/

const getAllGroupRoles = async (req, res) => {
const getPaginatedGroupRoles = async (req, res) => {
try {
const isDevMode = req.query?.dev === "true";
if (isDevMode) {
const latestDoc = req.query?.latestDoc;
const { groups, newLatestDoc } = await discordRolesModel.getPaginatedGroupRoles(latestDoc);
const discordId = req.userData?.discordId;
const groupsWithMembershipInfo = await discordRolesModel.enrichGroupDataWithMembershipInfo(discordId, groups);
return res.json({
message: "Roles fetched successfully!",
newLatestDoc: newLatestDoc,
groups: groupsWithMembershipInfo,
});
}
const { groups } = await discordRolesModel.getAllGroupRoles();
const discordId = req.userData?.discordId;
const groupsWithMembershipInfo = await discordRolesModel.enrichGroupDataWithMembershipInfo(discordId, groups);
Expand Down Expand Up @@ -341,7 +353,7 @@
const nickNameUpdatedUsers = [];
let counter = 0;
for (let i = 0; i < usersToBeEffected.length; i++) {
const { discordId, username, first_name: firstName } = usersToBeEffected[i];

Check warning on line 356 in controllers/discordactions.js

View workflow job for this annotation

GitHub Actions / build (20.11.x)

Variable Assigned to Object Injection Sink
try {
if (counter % 10 === 0 && counter !== 0) {
await new Promise((resolve) => setTimeout(resolve, 5500));
Expand All @@ -357,7 +369,7 @@
if (message) {
counter++;
totalNicknamesUpdated.count++;
nickNameUpdatedUsers.push(usersToBeEffected[i].id);

Check warning on line 372 in controllers/discordactions.js

View workflow job for this annotation

GitHub Actions / build (20.11.x)

Generic Object Injection Sink
}
}
} catch (error) {
Expand Down Expand Up @@ -431,7 +443,7 @@
});
await Promise.all(batch);

const allRolesInFirestore = await discordRolesModel.getAllGroupRoles();
const allRolesInFirestore = await discordRolesModel.getPaginatedGroupRoles();

return res.json({
response: allRolesInFirestore.groups,
Expand Down Expand Up @@ -534,7 +546,7 @@
module.exports = {
getGroupsRoleId,
createGroupRole,
getAllGroupRoles,
getPaginatedGroupRoles,
addGroupRoleToMember,
deleteRole,
updateDiscordImageForVerification,
Expand Down
24 changes: 24 additions & 0 deletions models/discordactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
* @param roleData { Object }: Data of the new role
* @returns {Promise<discordRoleModel|Object>}
*/

const getAllGroupRoles = async () => {
try {
const data = await discordRoleModel.get();
Expand All @@ -125,6 +126,28 @@
}
};

const getPaginatedGroupRoles = async (latestDoc) => {
try {
const data = await discordRoleModel
.orderBy("roleid")
.startAfter(latestDoc || 0)
.limit(18)
.get();
const groups = [];
data.forEach((doc) => {
const group = {
id: doc.id,
...doc.data(),
};
groups.push(group);
});
return { groups, newLatestDoc: data.docs[data.docs.length - 1]?.data().roleid };
} catch (err) {
logger.error("Error in getting all group-roles", err);
throw err;
}
};

/**
*
* @param groupRoleName String : name of the role
Expand Down Expand Up @@ -523,7 +546,7 @@

for (let i = 0; i < nicknameUpdateBatches.length; i++) {
const promises = [];
const usersStatusDocsBatch = nicknameUpdateBatches[i];

Check warning on line 549 in models/discordactions.js

View workflow job for this annotation

GitHub Actions / build (20.11.x)

Variable Assigned to Object Injection Sink
usersStatusDocsBatch.forEach((document) => {
const doc = document.data();
const userId = doc.userId;
Expand Down Expand Up @@ -1086,6 +1109,7 @@
removeMemberGroup,
getGroupRolesForUser,
getAllGroupRoles,
getPaginatedGroupRoles,
getGroupRoleByName,
updateGroupRole,
addGroupRoleToMember,
Expand Down
4 changes: 2 additions & 2 deletions routes/discordactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const {
createGroupRole,
getGroupsRoleId,
getAllGroupRoles,
getPaginatedGroupRoles,
addGroupRoleToMember,
deleteRole,
updateDiscordImageForVerification,
Expand Down Expand Up @@ -33,7 +33,7 @@
const router = express.Router();

router.post("/groups", authenticate, checkIsVerifiedDiscord, validateGroupRoleBody, createGroupRole);
router.get("/groups", authenticate, checkIsVerifiedDiscord, getAllGroupRoles);
router.get("/groups", authenticate, checkIsVerifiedDiscord, getPaginatedGroupRoles);
Dismissed Show dismissed Hide dismissed
router.delete("/groups/:groupId", authenticate, checkIsVerifiedDiscord, authorizeRoles([SUPERUSER]), deleteGroupRole);
router.post("/roles", authenticate, checkIsVerifiedDiscord, validateMemberRoleBody, addGroupRoleToMember);
router.get("/invite", authenticate, getUserDiscordInvite);
Expand Down
35 changes: 25 additions & 10 deletions test/unit/models/discordactions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const tasksModel = firestore.collection("tasks");

const {
createNewRole,
getAllGroupRoles,
getPaginatedGroupRoles,
isGroupRoleExists,
addGroupRoleToMember,
deleteRoleFromDatabase,
Expand Down Expand Up @@ -93,27 +93,42 @@ describe("discordactions", function () {
});
});

describe("getAllGroupRoles", function () {
let getStub;
describe("getPaginatedGroupRoles", function () {
let orderByStub, startAfterStub, limitStub, getStub;

beforeEach(function () {
getStub = sinon.stub(discordRoleModel, "get").resolves({
forEach: (callback) => groupData.forEach(callback),
orderByStub = sinon.stub();
startAfterStub = sinon.stub();
limitStub = sinon.stub();
getStub = sinon.stub();

orderByStub.returns({ startAfter: startAfterStub });
startAfterStub.returns({ limit: limitStub });
limitStub.returns({ get: getStub });
getStub.resolves({
docs: groupData.map((group) => ({
id: group.id,
data: () => group,
})),
});

sinon.stub(discordRoleModel, "orderBy").returns(orderByStub);
});

afterEach(function () {
getStub.restore();
sinon.restore();
});

it("should return all group-roles from the database", async function () {
const result = await getAllGroupRoles();
expect(result.groups).to.be.an("array");
it("should return paginated group-roles from the database", async function () {
const result = await getPaginatedGroupRoles();
expect(result).to.have.property("groups").that.is.an("array");
expect(result).to.have.property("newLatestDoc");
expect(result.groups.length).to.be.at.most(18); // Assuming the limit is 18 as per the function
});

it("should throw an error if getting group-roles fails", async function () {
getStub.rejects(new Error("Database error"));
return getAllGroupRoles().catch((err) => {
return getPaginatedGroupRoles().catch((err) => {
expect(err).to.be.an.instanceOf(Error);
expect(err.message).to.equal("Database error");
});
Expand Down
Loading