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/GitHub duplication #1818

Merged
merged 22 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
4017e99
Refactor : Modified callback api to have github user id
joyguptaa Dec 28, 2023
7dacd3e
Feat : Added API to add github_user_id to all users
joyguptaa Dec 28, 2023
8407103
Test : Added test for github_user_id script
joyguptaa Dec 28, 2023
d4ae3ac
Bug : Fixed logic while for checking github_user_id
joyguptaa Dec 28, 2023
9f0cc96
Chore : Minor Fixes
joyguptaa Jan 4, 2024
3a3d361
Refactor : Moved code to models
joyguptaa Jan 5, 2024
3a4c604
Merge branch 'develop' into feat/github-duplication
joyguptaa Jan 5, 2024
a8f3d7e
Test : Added failing mock data
joyguptaa Jan 5, 2024
483527c
Merge branch 'feat/github-duplication' of https://github.com/Real-Dev…
joyguptaa Jan 5, 2024
5787ca3
Merge branch 'develop' into feat/github-duplication
joyguptaa Jan 6, 2024
788f63d
Merge branch 'develop' into feat/github-duplication
joyguptaa Jan 7, 2024
8d70a3a
Merge branch 'develop' into feat/github-duplication
joyguptaa Jan 7, 2024
8aa5d6f
Feat : Updated API params
joyguptaa Jan 15, 2024
f1844d6
Feat : Added pagination logic to migrations API
joyguptaa Jan 15, 2024
78e6600
Merge branch 'feat/github-duplication' of https://github.com/Real-Dev…
joyguptaa Jan 15, 2024
61881fb
Merge branch 'develop' into feat/github-duplication
joyguptaa Jan 16, 2024
eded930
Test : Updated the test case
joyguptaa Jan 16, 2024
8f29087
Feat : Updated query params
joyguptaa Jan 16, 2024
8e1eb5f
Test : Updated test cases for migration api
joyguptaa Jan 16, 2024
1c3af94
Merge branch 'feat/github-duplication' of https://github.com/Real-Dev…
joyguptaa Jan 16, 2024
eacc712
Merge branch 'develop' into feat/github-duplication
joyguptaa Jan 17, 2024
86ae835
Merge branch 'develop' into feat/github-duplication
Ajeyakrishna-k Jan 18, 2024
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
Prev Previous commit
Next Next commit
Refactor : Moved code to models
  • Loading branch information
joyguptaa committed Jan 5, 2024
commit 3a3d361209fc03655f3313b8280903a04c66bf0b
64 changes: 6 additions & 58 deletions controllers/users.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const firestore = require("../utils/firestore");
const chaincodeQuery = require("../models/chaincodes");
const userQuery = require("../models/users");
const profileDiffsQuery = require("../models/profileDiffs");
Expand All @@ -16,7 +15,7 @@ const { getPaginationLink, getUsernamesFromPRs, getRoleToUpdate } = require("../
const { setInDiscordFalseScript, setUserDiscordNickname } = require("../services/discordService");
const { generateDiscordProfileImageUrl } = require("../utils/discord-actions");
const { addRoleToUser, getDiscordMembers } = require("../services/discordService");
const { fetchAllUsers } = require("../models/users");
const { fetchAllUsers, addGithubUserId } = require("../models/users");
const { getOverdueTasks } = require("../models/tasks");
const { getQualifiers } = require("../utils/helper");
const { parseSearchQuery } = require("../utils/users");
Expand Down Expand Up @@ -857,72 +856,21 @@ async function usersPatchHandler(req, res) {
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
}
const addGithubId = async (req, res) => {
const migrations = async (req, res) => {
const { action } = req.query;
if (action !== "adds-github-id") {
return res.status(400).json({
message: "Invalid action type",
});
}
const usersNotFound = [];
let countUserFound = 0;
let countUserNotFound = 0;

try {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization:
"Basic " + btoa(`${config.get("githubOauth.clientId")}:${config.get("githubOauth.clientSecret")}`),
},
};
const usersSnapshot = await firestore.collection("users").get();
const totalUsers = usersSnapshot.docs.length;
const batchCount = Math.ceil(totalUsers / 500);
// Create batch write operations for each batch of documents
for (let i = 0; i < batchCount; i++) {
const batchWrite = firestore.batch();
const batchWrites = [];
for (const userDoc of usersSnapshot.docs.slice(i * 500, (i + 1) * 500)) {
const githubUsername = userDoc.data().github_id;
const username = userDoc.data().username;
const userId = userDoc.id;
batchWrite.update(userDoc.ref, { github_user_id: null });

const getUserDetails = fetch(`https://api.github.com/users/${githubUsername}`, requestOptions)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
const githubUserId = data.id;
batchWrite.update(userDoc.ref, { github_user_id: `${githubUserId}` });
countUserFound++;
})
.catch((error) => {
countUserNotFound++;
const invalidUsers = { userId, username, githubUsername };
usersNotFound.push(invalidUsers);
logger.error("An error occurred at fetch:", error);
});
batchWrites.push(getUserDetails);
}
await Promise.all(batchWrites);
await batchWrite.commit();
}
const result = await addGithubUserId();
return res.status(200).json({
message: "Result of migration",
data: {
totalUsers: totalUsers,
usersUpdated: countUserFound,
usersNotUpdated: countUserNotFound,
invalidUsersDetails: usersNotFound,
},
data: result,
});
} catch (error) {
logger.error(`Error while Updating all users: ${error}`);
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
};
Expand Down Expand Up @@ -956,5 +904,5 @@ module.exports = {
updateDiscordUserNickname,
archiveUserIfNotInDiscord,
usersPatchHandler,
addGithubId,
migrations,
};
63 changes: 63 additions & 0 deletions models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,68 @@ const getNonNickNameSyncedUsers = async () => {
throw err;
}
};
const addGithubUserId = async () => {
try {
const usersNotFound = [];
let countUserFound = 0;
let countUserNotFound = 0;

const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization:
"Basic " + btoa(`${config.get("githubOauth.clientId")}:${config.get("githubOauth.clientSecret")}`),
},
};
const usersSnapshot = await firestore.collection("users").get();
const totalUsers = usersSnapshot.docs.length;
const batchCount = Math.ceil(totalUsers / 500);
// Create batch write operations for each batch of documents
for (let i = 0; i < batchCount; i++) {
const batchWrite = firestore.batch();
const batchWrites = [];
for (const userDoc of usersSnapshot.docs.slice(i * 500, (i + 1) * 500)) {
Ajeyakrishna-k marked this conversation as resolved.
Show resolved Hide resolved
if (userDoc.data().github_user_id) continue;
const githubUsername = userDoc.data().github_id;
const username = userDoc.data().username;
const userId = userDoc.id;
batchWrite.update(userDoc.ref, { github_user_id: null });
Ajeyakrishna-k marked this conversation as resolved.
Show resolved Hide resolved

const getUserDetails = fetch(`https://api.github.com/users/${githubUsername}`, requestOptions)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
const githubUserId = data.id;
batchWrite.update(userDoc.ref, { github_user_id: `${githubUserId}` });
countUserFound++;
})
.catch((error) => {
countUserNotFound++;
const invalidUsers = { userId, username, githubUsername };
usersNotFound.push(invalidUsers);
logger.error("An error occurred at fetch:", error);
});
batchWrites.push(getUserDetails);
}
await Promise.all(batchWrites);
await batchWrite.commit();
}
return {
totalUsers: totalUsers,
usersUpdated: countUserFound,
usersNotUpdated: countUserNotFound,
invalidUsersDetails: usersNotFound,
};
} catch (error) {
logger.error(`Error while Updating all users: ${error}`);
throw Error(error);
}
};

module.exports = {
addOrUpdate,
Expand Down Expand Up @@ -898,4 +960,5 @@ module.exports = {
fetchUsersListForMultipleValues,
fetchUserForKeyValue,
getNonNickNameSyncedUsers,
addGithubUserId,
};
2 changes: 1 addition & 1 deletion routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,5 @@
router.patch("/:userId", authenticate, authorizeRoles([SUPERUSER]), users.updateUser);
router.get("/suggestedUsers/:skillId", authenticate, authorizeRoles([SUPERUSER]), users.getSuggestedUsers);
// WARNING!! - One time Script/Route to do migration
router.post("/migrations", authenticate, authorizeRoles([SUPERUSER]), users.addGithubId);
router.post("/migrations", authenticate, authorizeRoles([SUPERUSER]), users.migrations);
Fixed Show fixed Hide fixed
module.exports = router;
Loading