Skip to content

Refactoring and Error Handling Enhancements #11

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

Merged
merged 5 commits into from
May 19, 2024
Merged
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nodejs-boilerplate",
"version": "1.0.4",
"version": "1.1.0",
"description": "[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)",
"main": "index.js",
"directories": {
Expand Down
146 changes: 77 additions & 69 deletions src/auth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,76 @@ function decryptToken(encryptedToken, iv) {
return decrypted;
}

async function getOrCreateUserFromGitHubProfile({ profile, accessToken }) {
const isAdmin = config.ADMIN_USERNAMES.includes(profile.username);
// Create a new user from GitHub API Profile data
const payload = {
githubId: profile.id,
nodeId: profile.nodeId,
displayName: profile.displayName,
username: profile.username,
profileUrl: profile.profileUrl,

avatarUrl: profile._json.avatar_url,
apiUrl: profile._json.url,
company: profile._json.company,
blog: profile._json.blog,
location: profile._json.location,
email: profile._json.email,
hireable: profile._json.hireable,
bio: profile._json.bio,
public_repos: profile._json.public_repos,
public_gists: profile._json.public_gists,
followers: profile._json.followers,
following: profile._json.following,
created_at: profile._json.created_at,
updated_at: profile._json.updated_at,

isDemo: false,
isVerified: true,
isAdmin,
};

let user = await getByGitHubId(profile.id);

const tokenInfo = encryptToken(accessToken);
if (user) {
if (user.isDeactivated) {
throw new AppError('user-is-deactivated', 'User is deactivated', 401);
}

// Update the user with the latest data
user = Object.assign(user, payload, {
accessToken: tokenInfo.token,
accessTokenIV: tokenInfo.iv,
updatedAt: new Date(),
});
await updateById(user._id, user);
} else {
// Create a new user
user = await create({
...payload,
accessToken: tokenInfo.token,
accessTokenIV: tokenInfo.iv,
});
}
const userObj = user.toObject();
const trimmedPayloadForSession = {
_id: userObj._id,
githubId: userObj.githubId,
nodeId: userObj.nodeId,
isAdmin: userObj.isAdmin,
isDeactivated: userObj.isDeactivated,
isDemo: userObj.isDemo,
// UI info
username: userObj.username,
displayName: userObj.displayName,
avatarUrl: userObj.avatarUrl,
email: userObj.email,
};
return trimmedPayloadForSession;
}

const getGitHubStrategy = () => {
return new GitHubStrategy(
{
Expand All @@ -44,76 +114,12 @@ const getGitHubStrategy = () => {
},
async (accessToken, refreshToken, profile, cb) => {
try {
const isAdmin = config.ADMIN_USERNAMES.includes(profile.username);
// Create a new user from GitHub API Profile data
const payload = {
githubId: profile.id,
nodeId: profile.nodeId,
displayName: profile.displayName,
username: profile.username,
profileUrl: profile.profileUrl,

avatarUrl: profile._json.avatar_url,
apiUrl: profile._json.url,
company: profile._json.company,
blog: profile._json.blog,
location: profile._json.location,
email: profile._json.email,
hireable: profile._json.hireable,
bio: profile._json.bio,
public_repos: profile._json.public_repos,
public_gists: profile._json.public_gists,
followers: profile._json.followers,
following: profile._json.following,
created_at: profile._json.created_at,
updated_at: profile._json.updated_at,

isDemo: false,
isVerified: true,
isAdmin,
};

let user = await getByGitHubId(profile.id);

const tokenInfo = encryptToken(accessToken);
if (user) {
if (user.isDeactivated) {
throw new AppError(
'user-is-deactivated',
'User is deactivated',
401
);
const trimmedPayloadForSession = await getOrCreateUserFromGitHubProfile(
{
profile,
accessToken,
}

// Update the user with the latest data
user = Object.assign(user, payload, {
accessToken: tokenInfo.token,
accessTokenIV: tokenInfo.iv,
updatedAt: new Date(),
});
await updateById(user._id, user);
} else {
// Create a new user
user = await create({
...payload,
accessToken: tokenInfo.token,
accessTokenIV: tokenInfo.iv,
});
}
const userObj = user.toObject();
const trimmedPayloadForSession = {
_id: userObj._id,
githubId: userObj.githubId,
nodeId: userObj.nodeId,
isAdmin: userObj.isAdmin,
isDeactivated: userObj.isDeactivated,
isDemo: userObj.isDemo,
// UI info
username: userObj.username,
displayName: userObj.displayName,
avatarUrl: userObj.avatarUrl,
email: userObj.email,
};
);

cb(null, trimmedPayloadForSession); // Pass the user object to the session
} catch (error) {
Expand All @@ -133,7 +139,9 @@ const clearAuthInfo = async (userId) => {
};

module.exports = {
getOrCreateUserFromGitHubProfile,
getGitHubStrategy,
clearAuthInfo,
encryptToken,
decryptToken,
};
3 changes: 0 additions & 3 deletions src/domains/product/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,6 @@ const routes = () => {
async (req, res, next) => {
try {
const item = await updateById(req.params.id, req.body);
if (!item) {
throw new AppError(`${model} not found`, `${model} not found`, 404);
}
res.status(200).json(item);
} catch (error) {
next(error);
Expand Down
11 changes: 9 additions & 2 deletions src/domains/product/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,22 +44,29 @@ const search = async (query) => {
const getById = async (id) => {
try {
const item = await Model.findById(id);
if (!item) {
throw new AppError(`${model} not found`, `${model} not found`, 404);
}
logger.info(`getById(): ${model} fetched`, { id });
return item;
} catch (error) {
logger.error(`getById(): Failed to get ${model}`, error);
throw new AppError(`Failed to get ${model}`, error.message);
throw new AppError(`Failed to get ${model}`, error.message, error.HTTPStatus || 400);
}
};

const updateById = async (id, data) => {
try {
const item = await Model.findByIdAndUpdate(id, data, { new: true });
if (!item) {
throw new AppError(`${model} not found`, `${model} not found`, 404);
}

logger.info(`updateById(): ${model} updated`, { id });
return item;
} catch (error) {
logger.error(`updateById(): Failed to update ${model}`, error);
throw new AppError(`Failed to update ${model}`, error.message);
throw new AppError(`Failed to update ${model}`, error.message, error.HTTPStatus || 400);
}
};

Expand Down
21 changes: 6 additions & 15 deletions src/domains/repository/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const routes = () => {
const router = express.Router();
logger.info(`Setting up routes for ${model}`);

// '/search'
router.get(
'/search',
logRequest({}),
Expand All @@ -46,6 +47,7 @@ const routes = () => {
}
);

// '/count',
router.get(
'/count',
logRequest({}),
Expand All @@ -60,6 +62,7 @@ const routes = () => {
}
);

// '/search-one'
router.post(
'/search-one',
logRequest({}),
Expand All @@ -75,7 +78,7 @@ const routes = () => {
}
);

// fetch repository details from GitHub API
// '/fetch-from-github' fetch repository details from GitHub API
router.post(
'/fetch-from-github',
logRequest({}),
Expand All @@ -95,6 +98,7 @@ const routes = () => {
}
);

//'/:id/follow'
router.get(
'/:id/follow',
logRequest({}),
Expand All @@ -110,20 +114,7 @@ const routes = () => {
}
);

router.post(
'/',
logRequest({}),
validateRequest({ schema: createSchema }),
async (req, res, next) => {
try {
const item = await create(req.body);
res.status(201).json(item);
} catch (error) {
next(error);
}
}
);

//'/:id',
router.get(
'/:id',
logRequest({}),
Expand Down
14 changes: 9 additions & 5 deletions src/domains/repository/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const Model = require('./schema');
const User = require('../user/schema');
const { AppError } = require('../../libraries/error-handling/AppError');

const { fetchRepoDetails } = require('../../libraries/util/githubUtils');
const github = require('../../libraries/util/githubUtils');
const { decryptToken } = require('../../auth');

const model = 'repository';
Expand Down Expand Up @@ -122,11 +122,15 @@ const searchOne = async (searchPayload) => {
const getById = async (id) => {
try {
const item = await Model.findById(id);
logger.info(`getById(): ${model} fetched`, { id, _id: item._id });
logger.info(`getById(): ${model} fetched`, { id, _id: item?._id });
return item;
} catch (error) {
logger.error(`getById(): Failed to get ${model}`, error);
throw new AppError(`Failed to get ${model}`, error.message);
throw new AppError(
`Failed to get ${model}`,
error.message,
error.HTTPStatus || 400
);
}
};

Expand Down Expand Up @@ -227,7 +231,7 @@ const fetchGitHubRepoDetails = async (owner, repo, user) => {
const { accessToken, accessTokenIV } = dbUser;
const token = decryptToken(accessToken, accessTokenIV);

const response = await fetchRepoDetails(owner, repo, token);
const response = await github.fetchRepoDetails(owner, repo, token);
// check if the repository already exists in the database by id node_id
// if it exists, update the repository details using mapSelectedGithubResponseToSchema
// else create the repository using mapGithubResponseToSchema
Expand Down Expand Up @@ -269,7 +273,7 @@ const followRepository = async (followerId, repositoryId) => {
const [repositoryUpdate, followerUserUpdate] = await Promise.all([
// Update csFollowers of the repository
Model.findByIdAndUpdate(repositoryId, {
$push: { csFollowers: { _id: followerId, date: Date.now() } },
$push: { csFollowers: { _id: followerId, date: Date.now() } },
}),

// Update csFollowingRepositories of the follower user
Expand Down
Loading