Skip to content
Snippets Groups Projects
Commit bebc1fe7 authored by michael.minelli's avatar michael.minelli
Browse files

Repo creation => Readability improvement (by try/catch removal)

parent d83a2ee0
Branches
No related tags found
No related merge requests found
Pipeline #30705 passed
...@@ -2,31 +2,40 @@ import express from 'express'; ...@@ -2,31 +2,40 @@ import express from 'express';
import logger from '../shared/logging/WinstonLogger'; import logger from '../shared/logging/WinstonLogger';
import GitlabManager from '../managers/GitlabManager'; import GitlabManager from '../managers/GitlabManager';
import DojoStatusCode from '../shared/types/Dojo/DojoStatusCode'; import DojoStatusCode from '../shared/types/Dojo/DojoStatusCode';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import { GitbeakerRequestError } from '@gitbeaker/requester-utils'; import { GitbeakerRequestError } from '@gitbeaker/requester-utils';
import * as Gitlab from '@gitbeaker/rest'; import * as Gitlab from '@gitbeaker/rest';
class GlobalHelper { class GlobalHelper {
async repositoryCreationError(message: string, error: unknown, req: express.Request, res: express.Response, gitlabError: DojoStatusCode, internalError: DojoStatusCode, repositoryToRemove?: Gitlab.ProjectSchema): Promise<void> { repoCreationFnExecCreator(req: express.Request, res: express.Response, gitlabError: DojoStatusCode, internalError: DojoStatusCode, repositoryToRemove?: Gitlab.ProjectSchema) {
logger.error(message); return async (toExec: () => Promise<unknown>, errorMessage?: string) => {
logger.error(JSON.stringify(error)); try {
return await toExec();
} catch ( error ) {
if ( errorMessage ) {
logger.error(errorMessage);
logger.error(JSON.stringify(error));
try { try {
if ( repositoryToRemove ) { if ( repositoryToRemove ) {
await GitlabManager.deleteRepository(repositoryToRemove.id); await GitlabManager.deleteRepository(repositoryToRemove.id);
} }
} catch ( deleteError ) { } catch ( deleteError ) {
logger.error('Repository deletion error'); logger.error('Repository deletion error');
logger.error(JSON.stringify(deleteError)); logger.error(JSON.stringify(deleteError));
} }
if ( error instanceof GitbeakerRequestError ) { if ( error instanceof GitbeakerRequestError ) {
return req.session.sendResponse(res, StatusCodes.INTERNAL_SERVER_ERROR, {}, `Unknown gitlab error: ${ message }`, gitlabError); req.session.sendResponse(res, StatusCodes.INTERNAL_SERVER_ERROR, {}, `Unknown gitlab error: ${ errorMessage }`, gitlabError);
return; throw error;
} }
return req.session.sendResponse(res, StatusCodes.INTERNAL_SERVER_ERROR, {}, `Unknown error: ${ message }`, internalError); req.session.sendResponse(res, StatusCodes.INTERNAL_SERVER_ERROR, {}, `Unknown error: ${ errorMessage }`, internalError);
throw error;
}
}
};
} }
} }
......
...@@ -109,26 +109,15 @@ class AssignmentRoutes implements RoutesManager { ...@@ -109,26 +109,15 @@ class AssignmentRoutes implements RoutesManager {
await new Promise(resolve => setTimeout(resolve, Config.gitlab.repository.timeoutAfterCreation)); await new Promise(resolve => setTimeout(resolve, Config.gitlab.repository.timeoutAfterCreation));
try { const repoCreationFnExec = GlobalHelper.repoCreationFnExecCreator(req, res, DojoStatusCode.ASSIGNMENT_CREATION_GITLAB_ERROR, DojoStatusCode.ASSIGNMENT_CREATION_INTERNAL_ERROR, repository);
await GitlabManager.protectBranch(repository.id, '*', true, Gitlab.AccessLevel.DEVELOPER, Gitlab.AccessLevel.DEVELOPER, Gitlab.AccessLevel.ADMIN);
await GitlabManager.addRepositoryBadge(repository.id, Config.gitlab.badges.pipeline.link, Config.gitlab.badges.pipeline.imageUrl, 'Pipeline Status');
} catch ( error ) {
return GlobalHelper.repositoryCreationError('Repo params error', error, req, res, DojoStatusCode.ASSIGNMENT_CREATION_GITLAB_ERROR, DojoStatusCode.ASSIGNMENT_CREATION_INTERNAL_ERROR, repository);
}
try { try {
await GitlabManager.deleteFile(repository.id, '.gitlab-ci.yml', 'Remove .gitlab-ci.yml'); await repoCreationFnExec(() => GitlabManager.protectBranch(repository.id, '*', true, Gitlab.AccessLevel.DEVELOPER, Gitlab.AccessLevel.DEVELOPER, Gitlab.AccessLevel.ADMIN), 'Branch protection modification error');
} catch ( error ) { /* empty */ } await repoCreationFnExec(() => GitlabManager.addRepositoryBadge(repository.id, Config.gitlab.badges.pipeline.link, Config.gitlab.badges.pipeline.imageUrl, 'Pipeline Status'), 'Pipeline badge addition error');
await repoCreationFnExec(() => GitlabManager.deleteFile(repository.id, '.gitlab-ci.yml', 'Remove .gitlab-ci.yml'));
await repoCreationFnExec(() => GitlabManager.createFile(repository.id, '.gitlab-ci.yml', fs.readFileSync(path.join(__dirname, '../../assets/assignment_gitlab_ci.yml'), 'base64'), 'Add .gitlab-ci.yml (DO NOT MODIFY THIS FILE)'), 'CI/CD file creation error');
try { await repoCreationFnExec(() => Promise.all(params.members.map(member => member.id).map(async (memberId: number): Promise<Gitlab.MemberSchema | false> => {
await GitlabManager.createFile(repository.id, '.gitlab-ci.yml', fs.readFileSync(path.join(__dirname, '../../assets/assignment_gitlab_ci.yml'), 'base64'), 'Add .gitlab-ci.yml (DO NOT MODIFY THIS FILE)');
} catch ( error ) {
return GlobalHelper.repositoryCreationError('CI file error', error, req, res, DojoStatusCode.ASSIGNMENT_CREATION_GITLAB_ERROR, DojoStatusCode.ASSIGNMENT_CREATION_INTERNAL_ERROR, repository);
}
try {
await Promise.all(params.members.map(member => member.id).map(async (memberId: number): Promise<Gitlab.MemberSchema | false> => {
try { try {
return await GitlabManager.addRepositoryMember(repository.id, memberId, Gitlab.AccessLevel.DEVELOPER); return await GitlabManager.addRepositoryMember(repository.id, memberId, Gitlab.AccessLevel.DEVELOPER);
} catch ( error ) { } catch ( error ) {
...@@ -136,35 +125,35 @@ class AssignmentRoutes implements RoutesManager { ...@@ -136,35 +125,35 @@ class AssignmentRoutes implements RoutesManager {
logger.error(JSON.stringify(error)); logger.error(JSON.stringify(error));
return false; return false;
} }
})); })), 'Add repository members error');
const assignment: Assignment = await db.assignment.create({ const assignment: Assignment = await repoCreationFnExec(() => db.assignment.create({
data: { data: {
name : repository.name, name : repository.name,
gitlabId : repository.id, gitlabId : repository.id,
gitlabLink : repository.web_url, gitlabLink : repository.web_url,
gitlabCreationInfo: repository as unknown as Prisma.JsonObject, gitlabCreationInfo: repository as unknown as Prisma.JsonObject,
gitlabLastInfo : repository as unknown as Prisma.JsonObject, gitlabLastInfo : repository as unknown as Prisma.JsonObject,
gitlabLastInfoDate: new Date(), gitlabLastInfoDate: new Date(),
staff : { staff : {
connectOrCreate: [ ...params.members.map(gitlabUser => { connectOrCreate: [ ...params.members.map(gitlabUser => {
return { return {
create: { create: {
id : gitlabUser.id, id : gitlabUser.id,
gitlabUsername: gitlabUser.name gitlabUsername: gitlabUser.name
}, },
where : { where : {
id: gitlabUser.id id: gitlabUser.id
} }
}; };
}) ] }) ]
} }
} }
}) as unknown as Assignment; }), 'Database error') as Assignment;
return req.session.sendResponse(res, StatusCodes.OK, assignment); return req.session.sendResponse(res, StatusCodes.OK, assignment);
} catch ( error ) { } catch ( error ) {
return GlobalHelper.repositoryCreationError('DB error', error, req, res, DojoStatusCode.ASSIGNMENT_CREATION_GITLAB_ERROR, DojoStatusCode.ASSIGNMENT_CREATION_INTERNAL_ERROR, repository); /* Empty */
} }
} }
......
...@@ -158,28 +158,21 @@ class ExerciseRoutes implements RoutesManager { ...@@ -158,28 +158,21 @@ class ExerciseRoutes implements RoutesManager {
await new Promise(resolve => setTimeout(resolve, Config.gitlab.repository.timeoutAfterCreation)); await new Promise(resolve => setTimeout(resolve, Config.gitlab.repository.timeoutAfterCreation));
try { const repoCreationFnExec = GlobalHelper.repoCreationFnExecCreator(req, res, DojoStatusCode.EXERCISE_CREATION_GITLAB_ERROR, DojoStatusCode.EXERCISE_CREATION_INTERNAL_ERROR, repository);
await GitlabManager.protectBranch(repository.id, '*', false, Gitlab.AccessLevel.DEVELOPER, Gitlab.AccessLevel.DEVELOPER, Gitlab.AccessLevel.ADMIN);
await GitlabManager.addRepositoryVariable(repository.id, 'DOJO_EXERCISE_ID', exerciseId, false, true); try {
await GitlabManager.addRepositoryVariable(repository.id, 'DOJO_SECRET', secret, false, true); await repoCreationFnExec(() => GitlabManager.protectBranch(repository.id, '*', false, Gitlab.AccessLevel.DEVELOPER, Gitlab.AccessLevel.DEVELOPER, Gitlab.AccessLevel.ADMIN), 'Branch protection modification error');
await GitlabManager.addRepositoryVariable(repository.id, 'DOJO_RESULTS_FOLDER', Config.exercise.pipelineResultsFolder, false, false); await repoCreationFnExec(() => GitlabManager.addRepositoryBadge(repository.id, Config.gitlab.badges.pipeline.link, Config.gitlab.badges.pipeline.imageUrl, 'Pipeline Status'), 'Pipeline badge addition error');
await GitlabManager.addRepositoryBadge(repository.id, Config.gitlab.badges.pipeline.link, Config.gitlab.badges.pipeline.imageUrl, 'Pipeline Status'); await repoCreationFnExec(async () => {
} catch ( error ) { await GitlabManager.addRepositoryVariable(repository.id, 'DOJO_EXERCISE_ID', exerciseId, false, true);
await GlobalHelper.repositoryCreationError('Repo params error', error, req, res, DojoStatusCode.EXERCISE_CREATION_GITLAB_ERROR, DojoStatusCode.EXERCISE_CREATION_INTERNAL_ERROR, repository); await GitlabManager.addRepositoryVariable(repository.id, 'DOJO_SECRET', secret, false, true);
return; await GitlabManager.addRepositoryVariable(repository.id, 'DOJO_RESULTS_FOLDER', Config.exercise.pipelineResultsFolder, false, false);
} }, 'Pipeline variables addition error');
try { await repoCreationFnExec(() => GitlabManager.updateFile(repository.id, '.gitlab-ci.yml', fs.readFileSync(path.join(__dirname, '../../assets/exercise_gitlab_ci.yml'), 'base64'), 'Add .gitlab-ci.yml (DO NOT MODIFY THIS FILE)'), 'CI/CD file update error');
await GitlabManager.updateFile(repository.id, '.gitlab-ci.yml', fs.readFileSync(path.join(__dirname, '../../assets/exercise_gitlab_ci.yml'), 'base64'), 'Add .gitlab-ci.yml (DO NOT MODIFY THIS FILE)');
} catch ( error ) {
await GlobalHelper.repositoryCreationError('CI file update error', error, req, res, DojoStatusCode.EXERCISE_CREATION_GITLAB_ERROR, DojoStatusCode.EXERCISE_CREATION_INTERNAL_ERROR, repository);
return;
}
try { await repoCreationFnExec(async () => Promise.all([ ...new Set([ ...assignment.staff.map(user => user.id), ...params.members.map(member => member.id) ]) ].map(async (memberId: number): Promise<Gitlab.MemberSchema | false> => {
await Promise.all([ ...new Set([ ...assignment.staff.map(user => user.id), ...params.members.map(member => member.id) ]) ].map(async (memberId: number): Promise<Gitlab.MemberSchema | false> => {
try { try {
return await GitlabManager.addRepositoryMember(repository.id, memberId, Gitlab.AccessLevel.DEVELOPER); return await GitlabManager.addRepositoryMember(repository.id, memberId, Gitlab.AccessLevel.DEVELOPER);
} catch ( error ) { } catch ( error ) {
...@@ -187,40 +180,38 @@ class ExerciseRoutes implements RoutesManager { ...@@ -187,40 +180,38 @@ class ExerciseRoutes implements RoutesManager {
logger.error(JSON.stringify(error)); logger.error(JSON.stringify(error));
return false; return false;
} }
})); })), 'Add repository members error');
const exercise: Exercise = await db.exercise.create({ const exercise: Exercise = await repoCreationFnExec(() => db.exercise.create({
data: { data: {
id : exerciseId, id : exerciseId,
assignmentName : assignment.name, assignmentName : assignment.name,
name : repository.name, name : repository.name,
secret : secret, secret : secret,
gitlabId : repository.id, gitlabId : repository.id,
gitlabLink : repository.web_url, gitlabLink : repository.web_url,
gitlabCreationInfo: repository as unknown as Prisma.JsonObject, gitlabCreationInfo: repository as unknown as Prisma.JsonObject,
gitlabLastInfo : repository as unknown as Prisma.JsonObject, gitlabLastInfo : repository as unknown as Prisma.JsonObject,
gitlabLastInfoDate: new Date(), gitlabLastInfoDate: new Date(),
members : { members : {
connectOrCreate: [ ...params.members.map(gitlabUser => { connectOrCreate: [ ...params.members.map(gitlabUser => {
return { return {
create: { create: {
id : gitlabUser.id, id : gitlabUser.id,
gitlabUsername: gitlabUser.name gitlabUsername: gitlabUser.name
}, },
where : { where : {
id: gitlabUser.id id: gitlabUser.id
} }
}; };
}) ] }) ]
} }
} }
}) as unknown as Exercise; })) as Exercise;
req.session.sendResponse(res, StatusCodes.OK, exercise); return req.session.sendResponse(res, StatusCodes.OK, exercise);
return;
} catch ( error ) { } catch ( error ) {
await GlobalHelper.repositoryCreationError('DB error', error, req, res, DojoStatusCode.EXERCISE_CREATION_GITLAB_ERROR, DojoStatusCode.EXERCISE_CREATION_INTERNAL_ERROR, repository); /* Empty */
return;
} }
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment