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

Add redirect util function for project custom actions #1865

Merged
merged 1 commit into from
Oct 29, 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
1 change: 0 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ const envVars = [
'GIVBACK_MAX_FACTOR',
'GIVBACK_MIN_FACTOR',
'DONATION_VERIFICAITON_EXPIRATION_HOURS',
'SYNC_USER_MODEL_SCORE_CRONJOB_EXPRESSION',
];

interface requiredEnv {
Expand Down
1 change: 1 addition & 0 deletions src/server/adminJs/adminJs-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface AdminJsContextInterface {
export interface AdminJsRequestInterface {
payload?: any;
record?: any;
rawHeaders?: any;
query?: {
recordIds?: string;
};
Expand Down
33 changes: 33 additions & 0 deletions src/server/adminJs/adminJsUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { logger } from '../../utils/logger';

/**
* Extracts the redirect URL from request headers for AdminJS actions
* @param request - The AdminJS action request object
* @param resourceName - The name of the resource (e.g., 'Project', 'User')
* @returns The URL to redirect to after action completion
*/
export const getRedirectUrl = (request: any, resourceName: string): string => {
const refererIndex =
request?.rawHeaders?.findIndex(h => h.toLowerCase() === 'referer') || -1;
const referrerUrl =
refererIndex !== -1 ? request.rawHeaders[refererIndex + 1] : false;
Comment on lines +10 to +13
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve referrer URL extraction logic.

The current implementation has potential issues with falsy values and type coercion.

-  const referrerUrl =
-    refererIndex !== -1 ? request.rawHeaders[refererIndex + 1] : false;
+  const referrerUrl =
+    refererIndex !== -1 && refererIndex + 1 < request.rawHeaders.length
+      ? request.rawHeaders[refererIndex + 1]
+      : null;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const refererIndex =
request?.rawHeaders?.findIndex(h => h.toLowerCase() === 'referer') || -1;
const referrerUrl =
refererIndex !== -1 ? request.rawHeaders[refererIndex + 1] : false;
const refererIndex =
request?.rawHeaders?.findIndex(h => h.toLowerCase() === 'referer') || -1;
const referrerUrl =
refererIndex !== -1 && refererIndex + 1 < request.rawHeaders.length
? request.rawHeaders[refererIndex + 1]
: null;


// Default fallback URL if no referer is found
const defaultUrl = `/admin/resources/${resourceName}`;

try {
if (referrerUrl) {
const url = new URL(referrerUrl);
// If it's the main list view (no search params), add a timestamp to force refresh
if (url.pathname === `/admin/resources/${resourceName}` && !url.search) {
return `${url.pathname}?timestamp=${Date.now()}`;
}
Comment on lines +22 to +24
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using higher precision timestamp.

Using Date.now() might not provide enough granularity for rapid successive requests, potentially leading to cache issues.

-        return `${url.pathname}?timestamp=${Date.now()}`;
+        return `${url.pathname}?timestamp=${Date.now()}.${performance.now().toString().replace('.', '')}`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (url.pathname === `/admin/resources/${resourceName}` && !url.search) {
return `${url.pathname}?timestamp=${Date.now()}`;
}
if (url.pathname === `/admin/resources/${resourceName}` && !url.search) {
return `${url.pathname}?timestamp=${Date.now()}.${performance.now().toString().replace('.', '')}`;
}

return url.pathname + url.search;
}
} catch (error) {
logger.error('Error parsing referrer URL:', error);
}

// Add timestamp to default URL as well
return `${defaultUrl}?timestamp=${Date.now()}`;
};
12 changes: 9 additions & 3 deletions src/server/adminJs/tabs/projectsTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import { refreshProjectEstimatedMatchingView } from '../../../services/projectVi
import { extractAdminJsReferrerUrlParams } from '../adminJs';
import { relateManyProjectsToQfRound } from '../../../repositories/qfRoundRepository2';
import { Category } from '../../../entities/category';
import { getRedirectUrl } from '../adminJsUtils';

// add queries depending on which filters were selected
export const buildProjectsQuery = (
Expand Down Expand Up @@ -188,6 +189,7 @@ export const verifyProjects = async (
request: AdminJsRequestInterface,
vouchedStatus: boolean = true,
) => {
const redirectUrl = getRedirectUrl(request, 'Project');
const { records, currentAdmin } = context;
try {
const projectIds = request?.query?.recordIds
Expand Down Expand Up @@ -236,7 +238,7 @@ export const verifyProjects = async (
throw error;
}
return {
redirectUrl: '/admin/resources/Project',
redirectUrl: redirectUrl,
records: records.map(record => {
record.toJSON(context.currentAdmin);
}),
Expand All @@ -254,6 +256,7 @@ export const updateStatusOfProjects = async (
request: AdminJsRequestInterface,
status,
) => {
const redirectUrl = getRedirectUrl(request, 'Project');
const { records, currentAdmin } = context;
const projectIds = request?.query?.recordIds
?.split(',')
Expand Down Expand Up @@ -319,7 +322,7 @@ export const updateStatusOfProjects = async (
]);
}
return {
redirectUrl: '/admin/resources/Project',
redirectUrl: redirectUrl,
records: records.map(record => {
record.toJSON(context.currentAdmin);
}),
Expand Down Expand Up @@ -415,6 +418,7 @@ export const addSingleProjectToQfRound = async (
request: AdminJsRequestInterface,
add: boolean = true,
) => {
const redirectUrl = getRedirectUrl(request, 'Project');
const { record, currentAdmin } = context;
let message = messages.PROJECTS_RELATED_TO_ACTIVE_QF_ROUND_SUCCESSFULLY;
const projectId = Number(request?.params?.recordId);
Expand All @@ -431,6 +435,7 @@ export const addSingleProjectToQfRound = async (
message = messages.THERE_IS_NOT_ANY_ACTIVE_QF_ROUND;
}
return {
redirectUrl: redirectUrl,
record: record.toJSON(currentAdmin),
notice: {
message,
Expand Down Expand Up @@ -523,6 +528,7 @@ export const listDelist = async (
request,
reviewStatus: ReviewStatus = ReviewStatus.Listed,
) => {
const redirectUrl = getRedirectUrl(request, 'Project');
const { records, currentAdmin } = context;
let listed;
switch (reviewStatus) {
Expand Down Expand Up @@ -586,7 +592,7 @@ export const listDelist = async (
throw error;
}
return {
redirectUrl: '/admin/resources/Project',
redirectUrl: redirectUrl,
records: records.map(record => {
record.toJSON(context.currentAdmin);
}),
Expand Down
Loading