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

Release 1.0.0 #110

Open
wants to merge 596 commits into
base: main
Choose a base branch
from
Open

Release 1.0.0 #110

wants to merge 596 commits into from

Conversation

Sourav-Tekdi
Copy link
Contributor

@Sourav-Tekdi Sourav-Tekdi commented Dec 5, 2024

Summary by CodeRabbit

Here are the release notes for this update:

Release Notes

  • New Features

    • Added Academic Years management functionality
    • Introduced Cohort Academic Year tracking
    • Enhanced user authentication with OTP and password reset capabilities
    • Added custom field management for cohorts
  • Improvements

    • Streamlined cohort search and filtering
    • Improved error handling across services
    • Updated authentication and authorization mechanisms
    • Enhanced user and tenant management
  • Breaking Changes

    • Removed Hasura-related modules and services
    • Discontinued attendance tracking functionality
    • Refactored service adapters to focus on PostgreSQL
  • Bug Fixes

    • Corrected import paths and module dependencies
    • Fixed validation and error response handling
    • Improved data consistency across services

poojakarma and others added 30 commits September 9, 2024 15:11
ERROR: 500 Internal Server Error on Create User API Endpoint
PS-2038: added changes for reset api and integrate email after reset successfully
Changes regarding 'Add tenantId column in “RolePrivilegesMapping” table'
Xitija and others added 28 commits December 24, 2024 17:04
Search support for mutiple mail ids
PS-2441 feat : Changes in backend for inconsistent attendance
PS-3252: Introduce Status field on program management
PS-3323: Adding New Fields from the backend
Added route config file for interface
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
1 Security Hotspot
C Reliability Rating on New Code (required ≥ A)
C Security Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 44

🔭 Outside diff range comments (5)
src/cohort/cohortadapter.ts (1)

Line range hint 11-15: Add default case and error handling to switch statement.

The switch statement lacks a default case and error handling for invalid adapter sources, which could lead to returning undefined.

Consider this improvement:

     switch (process.env.ADAPTERSOURCE) {
       case "postgres":
         adapter = this.postgresProvider;
         break;
+      default:
+        throw new Error(`Invalid adapter source: ${process.env.ADAPTERSOURCE}`);
     }
src/adapters/cohortMembersservicelocator.ts (1)

Line range hint 6-13: Improve type safety in method signatures.

The method uses any type for parameters which reduces type safety.

   createCohortMembers(
-    loginUser: any,
+    loginUser: User,
-    response: any,
+    response: Response,
     tenantId: string,
     deviceId: string,
     academicyearid: string
-  );
+  ): Promise<void>;
src/auth/auth.service.ts (1)

Line range hint 99-121: Enhance token refresh security.

The refreshToken method should validate the refresh token's expiration before attempting to refresh.

 async refreshToken(
   refreshToken: string,
   response: Response
 ): Promise<LoginResponse> {
   const apiId = APIID.REFRESH;
+  try {
+    const decoded: any = jwt_decode(refreshToken);
+    if (decoded.exp * 1000 < Date.now()) {
+      return APIResponse.error(
+        response,
+        apiId,
+        "Token Expired",
+        "Refresh token has expired",
+        HttpStatus.UNAUTHORIZED
+      );
+    }
+  } catch (error) {
+    return APIResponse.error(
+      response,
+      apiId,
+      "Invalid Token",
+      "Invalid refresh token format",
+      HttpStatus.UNAUTHORIZED
+    );
+  }
   const { access_token, expires_in, refresh_token, refresh_expires_in } =
.github/workflows/dev-pratham-eks-deployment.yaml (2)

Line range hint 48-52: Remove duplicate AWS credentials configuration.

The AWS credentials configuration step is duplicated. Remove the second occurrence as it's redundant.

🧰 Tools
🪛 yamllint (1.35.1)

[warning] 33-33: wrong indentation: expected 8 but found 7

(indentation)


[error] 34-34: trailing spaces

(trailing-spaces)


[error] 36-36: trailing spaces

(trailing-spaces)


Line range hint 77-89: Add deployment validation and rollback mechanism.

The current deployment process aggressively deletes resources without validation or rollback capability.

        kubectl delete deployment backend
        kubectl delete service backend
        kubectl delete cm backend-service-config
        kubectl apply -f manifest/backend-updated.yaml
        kubectl apply -f manifest/configmap.yaml
+       # Wait for deployment to complete
+       if ! kubectl rollout status deployment/backend --timeout=300s; then
+         echo "Deployment failed! Rolling back..."
+         kubectl rollout undo deployment/backend
+         exit 1
+       fi
        sleep 10
♻️ Duplicate comments (1)
manifest/backend.yaml (1)

31-39: ⚠️ Potential issue

Define resource limits for the cloudwatch-logs-agent container.

Resource limits are essential for container stability and cluster resource management. Add memory and CPU limits.

        resources: {}
+        resources:
+          limits:
+            memory: "256Mi"
+            cpu: "200m"
+          requests:
+            memory: "128Mi"
+            cpu: "100m"
🧰 Tools
🪛 GitHub Check: SonarCloud

[warning] 31-31: Memory limits should be enforced

Specify a memory limit for this container.

See more on SonarQube Cloud

🧹 Nitpick comments (50)
src/authRbac/authRbac.module.ts (1)

Line range hint 1-40: Architectural changes align with PostgreSQL migration.

The removal of HasuraModule and the focus on PostgreSQL-native functionality through TypeORM is a good architectural decision. This simplifies the stack and reduces complexity by eliminating an additional layer of abstraction.

Consider documenting the following aspects to ensure smooth maintenance:

  1. The JWT configuration strategy
  2. The role-based access control flow
  3. The relationship between Role, UserRoleMapping, and RolePrivilegeMapping entities
src/auth/auth.controller.ts (2)

69-75: Use consistent camelCase naming convention.

The destructuring uses snake_case (refresh_token) while TypeScript/NestJS convention is camelCase.

-    const { refresh_token: refreshToken } = body;
+    const { refreshToken } = body;

Also update the DTO to use camelCase:

export class RefreshTokenRequestBody {
  @ApiProperty()
  refreshToken: string;
}

86-86: LGTM! Proper async/await usage.

The async handling is correct, but consider the same camelCase naming convention suggestion as mentioned for the refreshToken method.

src/academicyears/academicyears.controller.ts (4)

49-62: Refactor to remove direct usage of @Res()

Directly using @Res() and manipulating the response object bypasses NestJS's automated response handling. It's recommended to return values or throw exceptions, allowing NestJS to handle the HTTP response status and formatting.

Refactor the method to return the result directly:

 async createAcademicYears(
     @Body() academicYearDto: AcademicYearDto,
-    @Res() response: Response,
     @Headers() headers
 ) {
     const tenantId = headers["tenantid"];
     if (!tenantId || !isUUID(tenantId)) {
         throw new BadRequestException(API_RESPONSES.TENANTID_VALIDATION);
     }
     const result = await this.academicYearAdapter
-        .buildAcademicYears()
         .createAcademicYear(academicYearDto, tenantId);
-    return response.status(result.statusCode).json(result);
+    return result;
 }

Ensure that createAcademicYear returns the appropriate data or throws exceptions as needed.


54-57: Extract tenant ID validation into a custom guard

Validating the tenantid header in each method leads to repetitive code. Consider creating a custom guard to handle tenant ID extraction and validation, promoting code reuse and adhering to DRY principles.

Example of a custom guard:

import { CanActivate, ExecutionContext, Injectable, BadRequestException } from '@nestjs/common';
import { isUUID } from 'class-validator';

@Injectable()
export class TenantGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const tenantId = request.headers['tenantid'];
    if (!tenantId || !isUUID(tenantId)) {
      throw new BadRequestException(API_RESPONSES.TENANTID_VALIDATION);
    }
    request.tenantId = tenantId;
    return true;
  }
}

Apply the guard to the controller:

 import { JwtAuthGuard } from "src/common/guards/keycloak.guard";
+import { TenantGuard } from "src/common/guards/tenant.guard";

 @UseGuards(JwtAuthGuard, TenantGuard)
 export class AcademicyearsController {

Then, access tenantId from the request in your methods:

async createAcademicYear(@Body() dto: AcademicYearDto, @Request() req) {
  const tenantId = req.tenantId;
  // ...
}

58-60: Simplify adapter method chaining

The use of .buildAcademicYears() may be unnecessary if it simply returns the adapter instance. Consider removing it to simplify the method call.

Update the method call:

 const result = await this.academicYearAdapter
-    .buildAcademicYears()
     .createAcademicYear(academicYearDto, tenantId);

25-35: Organize import statements

Rearrange the import statements to group them logically and alphabetically, separating external modules, third-party libraries, and local imports for improved readability.

src/adapters/postgres/cohortAcademicYear-adapter.ts (6)

16-17: Adjust class declaration formatting

The class declaration doesn't adhere to the project's formatting guidelines. Place the implements keyword on a new line and ensure the opening brace { is correctly positioned.

Apply this diff:

 @Injectable()
-export class CohortAcademicYearService implements IServiceLocatorCohortAcademicYear {
+export class CohortAcademicYearService
+  implements IServiceLocatorCohortAcademicYear
+{
🧰 Tools
🪛 eslint

[error] 16-17: Replace ·implements·IServiceLocatorCohortAcademicYear·{⏎ with ⏎··implements·IServiceLocatorCohortAcademicYear⏎{

(prettier/prettier)


23-24: Remove unnecessary comma and whitespace

There's an extraneous comma and whitespace after the constructor parameters. Clean up to adhere to formatting standards.

Apply this diff:

     @InjectRepository(CohortAcademicYear)
     private readonly cohortAcademicYearRepository: Repository<CohortAcademicYear>,
-  ) { }
+  ) {}
🧰 Tools
🪛 eslint

[error] 23-23: Delete ,

(prettier/prettier)


[error] 24-24: Delete ·

(prettier/prettier)


26-28: Format method parameters for readability

The method signature is lengthy and can be formatted across multiple lines to enhance readability.

Apply this diff:

-  async createCohortAcademicYear(tenantId: string, request: Request, cohortAcademicYearDto: CohortAcademicYearDto, response: Response) {
+  async createCohortAcademicYear(
+    tenantId: string,
+    request: Request,
+    cohortAcademicYearDto: CohortAcademicYearDto,
+    response: Response,
+  ) {
🧰 Tools
🪛 eslint

[error] 26-26: Replace tenantId:·string,·request:·Request,·cohortAcademicYearDto:·CohortAcademicYearDto,·response:·Response with ⏎····tenantId:·string,⏎····request:·Request,⏎····cohortAcademicYearDto:·CohortAcademicYearDto,⏎····response:·Response⏎··

(prettier/prettier)


34-34: Use consistent quotation marks

Replace single quotes with double quotes in string literals to maintain consistency with the project's style guidelines.

Apply this diff:

         where: { cohortId: cohortAcademicYearDto.cohortId, status: 'active' },
+        where: { cohortId: cohortAcademicYearDto.cohortId, status: "active" },
🧰 Tools
🪛 eslint

[error] 34-34: Replace 'active' with "active"

(prettier/prettier)


74-75: Format method call for clarity

Break long method arguments into multiple lines for better readability.

Apply this diff:

-      const createdAcademicYear = await this.insertCohortAcademicYear(cohortAcademicYearDto.cohortId, cohortAcademicYearDto.academicYearId, cohortAcademicYearDto.createdBy, cohortAcademicYearDto.updatedBy);
+      const createdAcademicYear = await this.insertCohortAcademicYear(
+        cohortAcademicYearDto.cohortId,
+        cohortAcademicYearDto.academicYearId,
+        cohortAcademicYearDto.createdBy,
+        cohortAcademicYearDto.updatedBy,
+      );
🧰 Tools
🪛 eslint

[error] 74-74: Replace cohortAcademicYearDto.cohortId,·cohortAcademicYearDto.academicYearId,·cohortAcademicYearDto.createdBy,·cohortAcademicYearDto.updatedBy with ⏎········cohortAcademicYearDto.cohortId,⏎········cohortAcademicYearDto.academicYearId,⏎········cohortAcademicYearDto.createdBy,⏎········cohortAcademicYearDto.updatedBy⏎······

(prettier/prettier)


86-95: Enhance error handling by logging exceptions

Currently, the catch block returns a generic error message. Logging the error can aid in debugging and monitoring.

Add error logging:

   } catch (error) {
+    console.error("Error in createCohortAcademicYear:", error);
     const errorMessage = error.message || "Internal server error";
     return APIResponse.error(
src/adapters/postgres/academicyears-adapter.ts (3)

16-16: Adjust class declaration formatting

Place the opening brace { on a new line to conform to the project's formatting guidelines.

Apply this diff:

 implements IServicelocatorAcademicyear {
+{
🧰 Tools
🪛 eslint

[error] 16-16: Replace · with

(prettier/prettier)


22-22: Remove trailing whitespace

There's unnecessary whitespace at the end of the line, which should be removed to adhere to style guidelines.

🧰 Tools
🪛 eslint

[error] 22-22: Delete ·

(prettier/prettier)


38-45: Ensure proper error messaging in tenant validation

In the tenant existence check, the error response uses API_RESPONSES.TENANT_NOTFOUND for both the title and message. Verify if this is intentional or if the message should be API_RESPONSES.NOT_FOUND.

Clarify the intended error message and adjust accordingly.

🧰 Tools
🪛 eslint

[error] 38-38: Replace ·where:·{·tenantId:·tenantId·}·}) with ⏎········where:·{·tenantId:·tenantId·},⏎······});

(prettier/prettier)

src/cohort/cohort.controller.ts (1)

127-133: Remove redundant assignment to cohortCreateDto.createdBy

The createdBy field is assigned twice. Remove the redundant assignment to keep the code clean.

Apply this diff:

-    cohortCreateDto.createdBy = userId;
src/adapters/postgres/cohortMembers-adapter.ts (3)

701-701: Use const instead of let for variables that are never reassigned

The variable cohortMembershipToUpdate is never reassigned after its initial assignment. Use const instead of let for better code clarity and to adhere to best practices.

Apply this diff:

-      let cohortMembershipToUpdate = await this.cohortMembersRepository.findOne({
+      const cohortMembershipToUpdate = await this.cohortMembersRepository.findOne({
         where: { cohortMembershipId: cohortMembershipId },
       });
🧰 Tools
🪛 eslint

[error] 701-701: 'cohortMembershipToUpdate' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 701-701: Insert ⏎········

(prettier/prettier)


715-715: Use const for the variable result

The variable result is not reassigned after its initial assignment. Change it to const for consistency and to follow best practices.

Apply this diff:

-      let result = await this.cohortMembersRepository.save(
+      const result = await this.cohortMembersRepository.save(
         cohortMembershipToUpdate
       );
🧰 Tools
🪛 eslint

[error] 715-715: 'result' is never reassigned. Use 'const' instead.

(prefer-const)


725-725: Avoid using the delete operator for better performance

Using the delete operator can negatively impact performance. Consider setting the property to undefined or using object destructuring to exclude the property.

Apply this diff:

-      delete cohortMembersUpdateDto.customFields;
+      cohortMembersUpdateDto.customFields = undefined;

Alternatively, create a new object without the customFields property:

const { customFields, ...updatedDto } = cohortMembersUpdateDto;
🧰 Tools
🪛 Biome (1.9.4)

[error] 725-725: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

src/adapters/postgres/cohort-adapter.ts (4)

2-2: Remove unused import jwt_decode

The imported jwt_decode module is not used in this file. Removing it will clean up the code and improve maintainability.

Apply this diff:

- import jwt_decode from "jwt-decode";

50-65: Remove commented-out code to enhance readability

The block of code from lines 50 to 65 is commented out. Removing unused code helps keep the codebase clean and easier to maintain.


528-528: Use Object.hasOwn() instead of hasOwnProperty

Directly accessing hasOwnProperty can lead to unexpected behavior if the object has a property with the same name. Use Object.hasOwn() for a safer check.

Apply this diff:

-            if (cohortUpdateDto.hasOwnProperty(key) && cohortUpdateDto[key] !== null) {
+            if (Object.hasOwn(cohortUpdateDto, key) && cohortUpdateDto[key] !== null) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 528-528: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)


284-286: Avoid using the delete operator for better performance

Using the delete operator can affect performance. Instead of deleting properties, set them to undefined or create a new object without the property.

However, note that in this case, the delete operator is not present in these lines. If the delete operator is used elsewhere, consider refactoring as suggested.

🧰 Tools
🪛 eslint

[error] 284-286: Replace ⏎······API_RESPONSES.COHORT_FIELD_DETAILS,⏎····) with API_RESPONSES.COHORT_FIELD_DETAILS);

(prettier/prettier)

src/adapters/postgres/fields-adapter.ts (1)

793-793: Use const instead of let for variables that are never reassigned

The variable tenantCond is assigned but never reassigned. Using const enhances code safety by preventing unintended reassignment.

Apply this diff:

-let tenantCond = tenantId? `"tenantId" = ${tenantId}` :`"tenantId" IS NULL`
+const tenantCond = tenantId ? `"tenantId" = ${tenantId}` : `"tenantId" IS NULL`
🧰 Tools
🪛 eslint

[error] 793-793: 'tenantCond' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 793-793: Replace "tenantId"·=·${tenantId}·:"tenantId"·IS·NULL`` with ⏎········?·"tenantId"·=·${tenantId}`⏎········:·`"tenantId"·IS·NULL`;`

(prettier/prettier)

src/adapters/postgres/user-adapter.ts (3)

1031-1031: Variable resKeycloak is never reassigned; use const instead of let

The variable resKeycloak is declared with let but is never reassigned after its initial assignment.

Apply this diff:

-let resKeycloak;
+const resKeycloak;
🧰 Tools
🪛 eslint

[error] 1031-1032: Delete

(prettier/prettier)


2015-2016: Variables error and success are never reassigned; use const instead of let

The variables error and success are declared with let but are never reassigned after their initial assignment.

Apply this diff:

-let error = [];
-let success = [];
+const error = [];
+const success = [];
🧰 Tools
🪛 eslint

[error] 2015-2015: 'error' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 2016-2016: 'success' is never reassigned. Use 'const' instead.

(prefer-const)


2126-2129: Improve error handling by checking for undefined errors

When accessing mailSend.result.email.errors, ensure that errors is defined to prevent runtime errors.

Adjust the code to safely access errors:

if (mailSend?.result?.email?.errors && mailSend.result.email.errors.length > 0) {
  const errorMessages = mailSend.result.email.errors.map((error: { error: string }) => error.error);
  const combinedErrorMessage = errorMessages.join(", ");
  throw new Error(`Error: ${combinedErrorMessage}`);
}
🧰 Tools
🪛 eslint

[error] 2126-2126: Replace mailSend?.result?.email?.errors·&&·mailSend.result.email.errors.length·>·0 with ⏎········mailSend?.result?.email?.errors·&&⏎········mailSend.result.email.errors.length·>·0⏎······

(prettier/prettier)


[error] 2127-2127: Replace (error:·{·error:·string;·})·=>·error.error with ⏎··········(error:·{·error:·string·})·=>·error.error⏎········

(prettier/prettier)

src/academicyears/dto/academicyears-search.dto.ts (1)

5-8: Property isActive should use the correct boolean transformation

The IsBoolean decorator checks if the value is a boolean type. However, when receiving data from query parameters, values are often strings. Consider using Transform to convert the input to a boolean.

Apply this change:

import { Transform } from 'class-transformer';

@ApiProperty({ description: "isActive", example: true })
@IsOptional()
@Transform(({ value }) => value === 'true' || value === true)
@IsBoolean()
isActive?: boolean;
src/academicyears/academicyearsadaptor.ts (1)

7-9: Consider using dependency injection tokens.

For better testability and configuration, consider using NestJS dependency injection tokens for the adapter source.

Example implementation:

// academic-year.constants.ts
export const ACADEMIC_YEAR_ADAPTER_SOURCE = 'ACADEMIC_YEAR_ADAPTER_SOURCE';

// academic-year.module.ts
{
  provide: ACADEMIC_YEAR_ADAPTER_SOURCE,
  useValue: process.env.ADAPTERSOURCE
}

// Then inject in constructor
constructor(
  @Inject(ACADEMIC_YEAR_ADAPTER_SOURCE) private readonly adapterSource: string,
  private readonly postgresProviders: PostgresAcademicYearService
)
src/academicyears/academicyears.module.ts (1)

14-14: Fix formatting: Remove trailing space.

Remove the trailing space before the closing curly brace to comply with prettier formatting rules.

-export class AcademicyearsModule { }
+export class AcademicyearsModule {}
🧰 Tools
🪛 eslint

[error] 14-14: Delete ·

(prettier/prettier)

src/adapters/privilegeservicelocator.ts (1)

14-14: Remove duplicate comment.

The comment for updatePrivilege appears twice in the file.

-  // updatePrivilege(privilegeId, request, privilegeDto)

Also applies to: 22-22

src/academicyears/entities/academicyears-entity.ts (2)

9-48: Add indexes for performance optimization.

Consider adding indexes for frequently queried fields like tenantId and isActive to improve query performance.

 @Entity("AcademicYears")
+@Index(["tenantId", "isActive"])
 export class AcademicYear {
   // ... existing code ...
 }

20-21: Add validation for session format.

The session field lacks validation constraints. Consider adding validation decorators to ensure consistent format.

+import { IsNotEmpty, Matches } from "class-validator";

 @Column({ type: "varchar", length: 15, name: "session" })
+@IsNotEmpty()
+@Matches(/^\d{4}-\d{4}$/, { message: "Session must be in YYYY-YYYY format" })
 session: string;
src/academicyears/dto/academicyears-create.dto.ts (1)

20-20: Add API documentation for optional field.

The isActive field lacks Swagger documentation.

+  @ApiProperty({ description: "Active status flag", example: true, default: true })
   isActive?: boolean;
src/adapters/fieldsservicelocator.ts (1)

15-20: Consider using a more specific return type.

The updateFields method and other methods in the interface should specify their return types for better type safety.

- updateFields(fieldId: any, request: any, fieldsUpdateDto: FieldsUpdateDto, response: Response);
+ updateFields(fieldId: string, request: any, fieldsUpdateDto: FieldsUpdateDto, response: Response): Promise<void>;
src/app.module.ts (1)

Line range hint 5-9: Remove commented code.

Consider removing or documenting the commented code blocks. If these modules are truly not in use for Shiksha 2.0, they should be removed rather than commented out.

src/cohort/cohort.module.ts (1)

27-38: Fix formatting issues.

Add a trailing comma after the last item in the TypeOrmModule.forFeature array.

      User,
-     Tenants
+     Tenants,
🧰 Tools
🪛 eslint

[error] 37-37: Insert ,

(prettier/prettier)

src/cohort/dto/cohort-create.dto.ts (2)

69-70: Remove commented code.

Remove the commented-out code to improve code readability.

Apply this diff:

-  // @Expose()
-  // status: string;

103-119: Remove redundant comments and consolidate field declarations.

The redundant //fieldValues comments and commented-out code block can be removed to improve code readability.

Apply this diff:

-  //fieldValues
-  //fieldValues
   @ApiPropertyOptional({
     type: [FieldValuesOptionDto],
     description: "The fieldValues Object",
   })
   @ValidateNested({ each: true })
   @Type(() => FieldValuesOptionDto)
   customFields: FieldValuesOptionDto[];
-  // @ApiPropertyOptional({
-  //   type: String,
-  //   description: "The fieldValues Object",
-  // })
-  // @IsString()
-  // @IsOptional()
-  // @Expose()
-  // fieldValues?: string;
src/adapters/postgres/postgres-module.ts (1)

67-67: Remove extra space in module class declaration.

Remove the extra space between the class declaration and the closing brace.

Apply this diff:

-export class PostgresModule { }
+export class PostgresModule {}
🧰 Tools
🪛 eslint

[error] 67-67: Delete ·

(prettier/prettier)

src/authRbac/authRbac.service.ts (1)

53-58: Standardize error message format.

The error messages should follow a consistent format. Currently, both error responses use "Bad Request" as the error type but have different message formats.

Apply this diff:

       return APIResponse.error(
         response,
         apiId,
         "Bad Request",
-        "User details or tenant not found for user",
+        "User details or tenant not found",
         HttpStatus.BAD_REQUEST
       );
     }

     const userRoles = await this.postgresRoleService.findUserRoleData(
       userData?.userId,
       tenantId
     );

     if (!userRoles?.length) {
       return APIResponse.error(
         response,
         apiId,
         "Bad Request",
-        "Roles not found for user",
+        "No roles assigned to user",
         HttpStatus.BAD_REQUEST
       );

Also applies to: 68-74

src/auth/auth.service.ts (1)

Line range hint 28-66: Add rate limiting for login attempts.

The login endpoint should implement rate limiting to prevent brute force attacks.

Consider using @nestjs/throttler decorator to add rate limiting:

import { Throttle } from '@nestjs/throttler';

@Throttle(5, 60) // 5 attempts per minute
async login(authDto, response: Response) {
  // existing code
}
src/adapters/postgres/rbac/privilegerole.adapter.ts (1)

83-89: Remove unnecessary try-catch block.

The try-catch block that only rethrows the error is redundant and can be removed.

 public async deleteByRoleId(roleId: string) {
-  try {
-    await this.rolePrivilegeMappingRepository.delete({ roleId });
-  } catch (error) {
-    throw error;
-  }
+  await this.rolePrivilegeMappingRepository.delete({ roleId });
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 87-87: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)

src/adapters/postgres/rbac/privilege-adapter.ts (1)

291-297: Optimize privilege response mapping.

The mapping of privilege response can be optimized using array methods.

-      const privilegeResponseArray: PrivilegeResponseDto[] = result.map(
-        (item: any) => {
-          const privilegeDto = new PrivilegeDto(item);
-          privilegeDto.title = item.name;
-          return new PrivilegeResponseDto(privilegeDto);
-        }
-      );
+      const privilegeResponseArray: PrivilegeResponseDto[] = result.map((item: any) => 
+        new PrivilegeResponseDto({
+          ...new PrivilegeDto(item),
+          title: item.name
+        })
+      );
src/adapters/postgres/rbac/role-adapter.ts (1)

389-391: Use TypeORM query builder for tenant check.

Replace raw SQL query with TypeORM query builder to maintain consistency and type safety.

 public async checkTenantID(tenantId) {
-  const query = `SELECT "tenantId" FROM public."Tenants"
-      where "tenantId"= $1 `;
-  const response = await this.roleRepository.query(query, [tenantId]);
+  const response = await this.roleRepository
+    .createQueryBuilder('tenant')
+    .select('tenant.tenantId')
+    .from('Tenants', 'tenant')
+    .where('tenant.tenantId = :tenantId', { tenantId })
+    .getRawMany();
   if (response.length > 0) {
     return true;
   }
   return false;
 }
.github/workflows/tekdi-server-deployment.yaml (2)

24-24: Add error handling for .env file creation.

The echo command writing to .env could fail silently. Consider adding error handling.

-               echo '${{ secrets.QA_ENV }}"' > .env
+               if ! echo '${{ secrets.QA_ENV }}"' > .env; then
+                 echo "Failed to create .env file"
+                 exit 1
+               fi

8-9: Add job failure notification.

Consider adding a notification step (e.g., Slack, email) for deployment failures to ensure timely response to issues.

🧰 Tools
🪛 yamllint (1.35.1)

[warning] 8-8: wrong indentation: expected 5 but found 4

(indentation)

manifest/backend.yaml (1)

35-36: Use environment variables for AWS region configuration.

Hard-coding the AWS region reduces flexibility. Consider using environment variables or ConfigMap.

-            value: ap-south-1
+            valueFrom:
+              configMapKeyRef:
+                name: aws-config
+                key: AWS_REGION
package.json (1)

24-31: Align NestJS package versions.

There's inconsistency in NestJS package versions. Some are ^8.0.0 while others are ^8.4.7.

Consider updating all NestJS packages to the same minor version for consistency:

-    "@nestjs/core": "^8.0.0",
+    "@nestjs/core": "^8.4.7",
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7f9c902 and 4e506ab.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (82)
  • .coderabbit.yaml (1 hunks)
  • .eslintrc.js (1 hunks)
  • .github/workflows/dev-pratham-eks-deployment.yaml (3 hunks)
  • .github/workflows/tekdi-server-deployment.yaml (1 hunks)
  • manifest/backend.yaml (1 hunks)
  • package.json (3 hunks)
  • src/academicyears/academicyears.controller.ts (1 hunks)
  • src/academicyears/academicyears.module.ts (1 hunks)
  • src/academicyears/academicyearsadaptor.ts (1 hunks)
  • src/academicyears/dto/academicyears-create.dto.ts (1 hunks)
  • src/academicyears/dto/academicyears-search.dto.ts (1 hunks)
  • src/academicyears/entities/academicyears-entity.ts (1 hunks)
  • src/adapters/academicyearsservicelocater.ts (1 hunks)
  • src/adapters/assignprivilegelocater.ts (1 hunks)
  • src/adapters/assignroleservicelocater.ts (1 hunks)
  • src/adapters/attendanceservicelocator.ts (0 hunks)
  • src/adapters/cohortMembersservicelocator.ts (2 hunks)
  • src/adapters/cohortacademicyearservicelocator.ts (1 hunks)
  • src/adapters/cohortservicelocator.ts (1 hunks)
  • src/adapters/configservicelocator.ts (0 hunks)
  • src/adapters/courseservicelocator.ts (0 hunks)
  • src/adapters/diksha/dikshaCourse.adapter.ts (0 hunks)
  • src/adapters/fieldsservicelocator.ts (1 hunks)
  • src/adapters/hasura/attendance.adapter.ts (0 hunks)
  • src/adapters/hasura/cohort.adapter.ts (0 hunks)
  • src/adapters/hasura/cohortMembers.adapter.ts (0 hunks)
  • src/adapters/hasura/config.adapter.ts (0 hunks)
  • src/adapters/hasura/courseTracking.adapter.ts (0 hunks)
  • src/adapters/hasura/fields.adapter.ts (0 hunks)
  • src/adapters/hasura/hasura.module.ts (0 hunks)
  • src/adapters/hasura/rbac/assignrole.adapter.ts (0 hunks)
  • src/adapters/hasura/rbac/privilege.adapter.ts (0 hunks)
  • src/adapters/hasura/rbac/privilegerole.adapter.ts (0 hunks)
  • src/adapters/hasura/rbac/role.adapter.ts (0 hunks)
  • src/adapters/hasura/services/fields.service.ts (0 hunks)
  • src/adapters/hasura/user.adapter.ts (0 hunks)
  • src/adapters/hasura/userTenantMapping.adapter.ts (0 hunks)
  • src/adapters/postgres/academicyears-adapter.ts (1 hunks)
  • src/adapters/postgres/attendance-adapter.ts (0 hunks)
  • src/adapters/postgres/cohort-adapter.ts (3 hunks)
  • src/adapters/postgres/cohortAcademicYear-adapter.ts (1 hunks)
  • src/adapters/postgres/cohortMembers-adapter.ts (8 hunks)
  • src/adapters/postgres/fields-adapter.ts (1 hunks)
  • src/adapters/postgres/postgres-module.ts (1 hunks)
  • src/adapters/postgres/potsgres-module.ts (0 hunks)
  • src/adapters/postgres/rbac/assignrole-adapter.ts (9 hunks)
  • src/adapters/postgres/rbac/privilege-adapter.ts (8 hunks)
  • src/adapters/postgres/rbac/privilegerole.adapter.ts (1 hunks)
  • src/adapters/postgres/rbac/role-adapter.ts (9 hunks)
  • src/adapters/postgres/user-adapter.ts (10 hunks)
  • src/adapters/postgres/userTenantMapping-adapter.ts (1 hunks)
  • src/adapters/privilegeservicelocator.ts (1 hunks)
  • src/adapters/questionservicelocator.ts (0 hunks)
  • src/adapters/rbacservicelocator.ts (1 hunks)
  • src/adapters/userservicelocator.ts (2 hunks)
  • src/adapters/usertenantmappinglocator.ts (1 hunks)
  • src/app.module.ts (2 hunks)
  • src/app.service.ts (0 hunks)
  • src/attendance/attendance.controller.spec.ts (0 hunks)
  • src/attendance/attendance.controller.ts (0 hunks)
  • src/attendance/attendance.module.ts (0 hunks)
  • src/attendance/attendanceadapter.ts (0 hunks)
  • src/attendance/dto/attendance-date.dto.ts (0 hunks)
  • src/attendance/dto/attendance-response.dto.ts (0 hunks)
  • src/attendance/dto/attendance-search.dto.ts (0 hunks)
  • src/attendance/dto/attendance-stats.dto.ts (0 hunks)
  • src/attendance/dto/attendance.dto.ts (0 hunks)
  • src/attendance/entities/attendance.entity.ts (0 hunks)
  • src/attendance/interfaces/attendance.interface.ts (0 hunks)
  • src/attendance/utils/file-upload.utils.ts (0 hunks)
  • src/auth/auth.controller.ts (3 hunks)
  • src/auth/auth.module.ts (1 hunks)
  • src/auth/auth.service.ts (4 hunks)
  • src/authRbac/authRbac.controller.ts (2 hunks)
  • src/authRbac/authRbac.module.ts (1 hunks)
  • src/authRbac/authRbac.service.ts (4 hunks)
  • src/cohort/cohort.controller.ts (6 hunks)
  • src/cohort/cohort.module.ts (1 hunks)
  • src/cohort/cohort.service.ts (0 hunks)
  • src/cohort/cohortadapter.ts (1 hunks)
  • src/cohort/dto/cohort-create.dto.ts (3 hunks)
  • src/cohort/dto/cohort-search.dto.ts (5 hunks)
⛔ Files not processed due to max files limit (53)
  • src/cohort/dto/cohort-update.dto.ts
  • src/cohort/dto/cohort.dto.ts
  • src/cohort/dto/query-params.dto.ts
  • src/cohort/entities/cohort.entity.ts
  • src/cohort/entities/state.entity.ts
  • src/cohortAcademicYear/cohortAcademicYear.controller.ts
  • src/cohortAcademicYear/cohortAcademicYear.module.ts
  • src/cohortAcademicYear/cohortacademicyearsadaptor.ts
  • src/cohortAcademicYear/dto/cohort-academicyear.dto.ts
  • src/cohortAcademicYear/entities/cohortAcademicYear.entity.ts
  • src/cohortMembers/cohortMembers.controller.ts
  • src/cohortMembers/cohortMembers.module.ts
  • src/cohortMembers/cohortMembersadapter.ts
  • src/cohortMembers/dto/bulkMember-create.dto.ts
  • src/cohortMembers/dto/cohortMember-update.dto.ts
  • src/cohortMembers/dto/cohortMembers-search.dto.ts
  • src/cohortMembers/dto/cohortMembers.dto.ts
  • src/cohortMembers/entities/cohort-member.entity.ts
  • src/common-dto/userSegment.dto.ts
  • src/common/database.module.ts
  • src/common/decorators/permission.decorator.ts
  • src/common/filters/exception.filter.ts
  • src/common/guards/keycloak.guard.ts
  • src/common/guards/keycloak.strategy.ts
  • src/common/logger/LoggerUtil.ts
  • src/common/pipes/date-validation.pipe.ts
  • src/common/responses/response.ts
  • src/common/services/upload-file.ts
  • src/common/utils/api-id.config.ts
  • src/common/utils/auth-util.ts
  • src/common/utils/custom-field-validation.ts
  • src/common/utils/formatTimeConversion.ts
  • src/common/utils/http-service.ts
  • src/common/utils/jwt-token.ts
  • src/common/utils/keycloak.adapter.util.ts
  • src/common/utils/notification.axios.ts
  • src/common/utils/response.messages.ts
  • src/configs/config.controller.spec.ts
  • src/configs/config.controller.ts
  • src/configs/configsadapter.ts
  • src/configs/configuration.module.ts
  • src/configs/dto/config-search.dto.ts
  • src/configs/dto/config.dto.ts
  • src/constants/routeconfig.js
  • src/course/course.controller.ts
  • src/course/course.module.ts
  • src/courseTracking/courseTracking.controller.ts
  • src/courseTracking/courseTracking.module.ts
  • src/courseTracking/dto/courseTracking.dto.ts
  • src/fieldOptions/blocks.json
  • src/fieldOptions/districts.json
  • src/fieldOptions/states.json
  • src/fields/dto/field-values-create.dto.ts
💤 Files with no reviewable changes (35)
  • src/app.service.ts
  • src/attendance/dto/attendance-response.dto.ts
  • src/attendance/interfaces/attendance.interface.ts
  • src/adapters/postgres/potsgres-module.ts
  • src/attendance/attendance.controller.spec.ts
  • src/adapters/hasura/hasura.module.ts
  • src/adapters/attendanceservicelocator.ts
  • src/attendance/attendanceadapter.ts
  • src/adapters/hasura/courseTracking.adapter.ts
  • src/adapters/courseservicelocator.ts
  • src/attendance/dto/attendance-date.dto.ts
  • src/attendance/attendance.module.ts
  • src/adapters/configservicelocator.ts
  • src/adapters/hasura/user.adapter.ts
  • src/adapters/hasura/userTenantMapping.adapter.ts
  • src/adapters/hasura/config.adapter.ts
  • src/attendance/entities/attendance.entity.ts
  • src/adapters/questionservicelocator.ts
  • src/attendance/attendance.controller.ts
  • src/adapters/hasura/cohort.adapter.ts
  • src/adapters/diksha/dikshaCourse.adapter.ts
  • src/attendance/utils/file-upload.utils.ts
  • src/adapters/hasura/rbac/assignrole.adapter.ts
  • src/adapters/postgres/attendance-adapter.ts
  • src/adapters/hasura/fields.adapter.ts
  • src/attendance/dto/attendance-search.dto.ts
  • src/attendance/dto/attendance-stats.dto.ts
  • src/adapters/hasura/rbac/privilegerole.adapter.ts
  • src/adapters/hasura/attendance.adapter.ts
  • src/adapters/hasura/services/fields.service.ts
  • src/adapters/hasura/rbac/role.adapter.ts
  • src/adapters/hasura/rbac/privilege.adapter.ts
  • src/adapters/hasura/cohortMembers.adapter.ts
  • src/cohort/cohort.service.ts
  • src/attendance/dto/attendance.dto.ts
✅ Files skipped from review due to trivial changes (7)
  • .eslintrc.js
  • src/adapters/rbacservicelocator.ts
  • src/adapters/usertenantmappinglocator.ts
  • src/adapters/assignprivilegelocater.ts
  • src/adapters/postgres/userTenantMapping-adapter.ts
  • src/adapters/assignroleservicelocater.ts
  • src/adapters/postgres/rbac/assignrole-adapter.ts
🧰 Additional context used
📓 Path-based instructions (35)
src/academicyears/academicyears.module.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/authRbac/authRbac.module.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/academicyears/dto/academicyears-create.dto.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/cohortacademicyearservicelocator.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/authRbac/authRbac.controller.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/academicyears/entities/academicyears-entity.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/academicyears/dto/academicyears-search.dto.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/academicyears/academicyearsadaptor.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/authRbac/authRbac.service.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/auth/auth.service.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/cohort/cohortadapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/rbac/privilege-adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/auth/auth.module.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/cohort/dto/cohort-create.dto.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/auth/auth.controller.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/academicyearsservicelocater.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/cohort/cohort.module.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/rbac/role-adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/rbac/privilegerole.adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/academicyears-adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/app.module.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/cohortMembersservicelocator.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/postgres-module.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/userservicelocator.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/cohortAcademicYear-adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/fieldsservicelocator.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/fields-adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/cohort/dto/cohort-search.dto.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/academicyears/academicyears.controller.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/cohort/cohort.controller.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/privilegeservicelocator.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/cohort-adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/cohortMembers-adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/postgres/user-adapter.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
src/adapters/cohortservicelocator.ts (1)

Pattern **/*.ts: "Review the JavaScript code for conformity with the Google JavaScript style guide, highlighting any deviations. Ensure that:

  • The code adheres to best practices associated with nodejs.
  • The code adheres to best practices associated with nestjs framework.
  • The code adheres to best practices recommended for performance.
  • The code adheres to similar naming conventions for controllers, models, services, methods, variables."
🪛 eslint
src/academicyears/academicyears.module.ts

[error] 14-14: Delete ·

(prettier/prettier)

src/adapters/cohortacademicyearservicelocator.ts

[error] 5-5: Delete ··

(prettier/prettier)


[error] 6-6: Delete ····

(prettier/prettier)


[error] 7-7: Delete ····

(prettier/prettier)


[error] 8-8: Replace ········ with ····

(prettier/prettier)


[error] 9-9: Delete ····

(prettier/prettier)


[error] 10-10: Delete ··

(prettier/prettier)


[error] 11-11: Insert

(prettier/prettier)

src/auth/auth.service.ts

[error] 26-26: Delete ·

(prettier/prettier)

src/cohort/cohort.module.ts

[error] 24-25: Delete

(prettier/prettier)


[error] 37-37: Insert ,

(prettier/prettier)


[error] 53-53: Delete ·

(prettier/prettier)

src/adapters/postgres/academicyears-adapter.ts

[error] 16-16: Replace · with

(prettier/prettier)


[error] 22-22: Delete ·

(prettier/prettier)


[error] 38-38: Replace ·where:·{·tenantId:·tenantId·}·}) with ⏎········where:·{·tenantId:·tenantId·},⏎······});

(prettier/prettier)


[error] 172-172: Replace ·where:·{·id:·id·} with ⏎········where:·{·id:·id·},⏎·····

(prettier/prettier)

src/adapters/postgres/postgres-module.ts

[error] 55-55: Insert ,

(prettier/prettier)


[error] 67-67: Delete ·

(prettier/prettier)

src/adapters/userservicelocator.ts

[error] 20-20: Replace request:·any,·userDto:·UserCreateDto,·academicYearId:·string,·response:·Response with ⏎····request:·any,⏎····userDto:·UserCreateDto,⏎····academicYearId:·string,⏎····response:·Response⏎··

(prettier/prettier)


[error] 36-36: Replace request:·any,·username:·string,·redirectUrl:·string,·response:·Response with ⏎····request:·any,⏎····username:·string,⏎····redirectUrl:·string,⏎····response:·Response⏎··

(prettier/prettier)


[error] 40-40: Replace body:·SendPasswordResetOTPDto,·response:·Response with ⏎····body:·SendPasswordResetOTPDto,⏎····response:·Response⏎··

(prettier/prettier)

src/adapters/postgres/cohortAcademicYear-adapter.ts

[error] 16-17: Replace ·implements·IServiceLocatorCohortAcademicYear·{⏎ with ⏎··implements·IServiceLocatorCohortAcademicYear⏎{

(prettier/prettier)


[error] 23-23: Delete ,

(prettier/prettier)


[error] 24-24: Delete ·

(prettier/prettier)


[error] 26-26: Replace tenantId:·string,·request:·Request,·cohortAcademicYearDto:·CohortAcademicYearDto,·response:·Response with ⏎····tenantId:·string,⏎····request:·Request,⏎····cohortAcademicYearDto:·CohortAcademicYearDto,⏎····response:·Response⏎··

(prettier/prettier)


[error] 34-34: Replace 'active' with "active"

(prettier/prettier)


[error] 74-74: Replace cohortAcademicYearDto.cohortId,·cohortAcademicYearDto.academicYearId,·cohortAcademicYearDto.createdBy,·cohortAcademicYearDto.updatedBy with ⏎········cohortAcademicYearDto.cohortId,⏎········cohortAcademicYearDto.academicYearId,⏎········cohortAcademicYearDto.createdBy,⏎········cohortAcademicYearDto.updatedBy⏎······

(prettier/prettier)


[error] 84-85: Delete

(prettier/prettier)


[error] 134-135: Delete

(prettier/prettier)

src/adapters/postgres/fields-adapter.ts

[error] 34-34: Delete ·

(prettier/prettier)


[error] 104-104: Insert ;

(prettier/prettier)


[error] 388-388: Insert ;

(prettier/prettier)


[error] 460-460: Insert ;

(prettier/prettier)


[error] 509-509: Replace ·fieldsData.fieldParams·&& with ⏎········fieldsData.fieldParams·&&⏎·······

(prettier/prettier)


[error] 635-635: Insert ;

(prettier/prettier)


[error] 670-673: Replace ⏎········${API_RESPONSES.SERVER_ERROR},⏎········Error:·${e.message},⏎······) with ``${API_RESPONSES.SERVER_ERROR}Error:·${e.message}`);`

(prettier/prettier)


[error] 769-772: Replace ⏎········${API_RESPONSES.SERVER_ERROR},⏎········Error:·${e.message},⏎······) with ``${API_RESPONSES.SERVER_ERROR}Error:·${e.message}`);`

(prettier/prettier)


[error] 793-793: 'tenantCond' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 793-793: Replace "tenantId"·=·${tenantId}·:"tenantId"·IS·NULL`` with ⏎········?·"tenantId"·=·${tenantId}`⏎········:·`"tenantId"·IS·NULL`;`

(prettier/prettier)


[error] 840-840: Insert ;

(prettier/prettier)


[error] 903-903: Insert ;

(prettier/prettier)


[error] 950-950: Insert ;

(prettier/prettier)


[error] 1052-1055: Replace ⏎········${API_RESPONSES.SERVER_ERROR},⏎········Error:·${e.message},⏎······) with ``${API_RESPONSES.SERVER_ERROR}Error:·${e.message}`);`

(prettier/prettier)


[error] 1281-1284: Replace ⏎········${API_RESPONSES.SERVER_ERROR},⏎········Error:·${e.message},⏎······) with ``${API_RESPONSES.SERVER_ERROR}Error:·${e.message}`);`

(prettier/prettier)


[error] 1407-1410: Replace ⏎········${API_RESPONSES.SERVER_ERROR},⏎········Error:·${e.message},⏎······) with ``${API_RESPONSES.SERVER_ERROR}Error:·${e.message}`);`

(prettier/prettier)


[error] 1468-1468: Delete ··

(prettier/prettier)


[error] 1469-1469: Delete ··

(prettier/prettier)


[error] 1653-1656: Replace ⏎········${API_RESPONSES.SERVER_ERROR},⏎········Error:·${e.message},⏎······) with ``${API_RESPONSES.SERVER_ERROR}Error:·${e.message}`);`

(prettier/prettier)

src/cohort/dto/cohort-search.dto.ts

[error] 137-137: Don't use {} as a type. {} actually means "any non-nullish value".

  • If you want a type meaning "any object", you probably want Record<string, unknown> instead.
  • If you want a type meaning "any value", you probably want unknown instead.
  • If you want a type meaning "empty object", you probably want Record<string, never> instead.

(@typescript-eslint/ban-types)

src/adapters/postgres/cohort-adapter.ts

[error] 45-45: Delete ·

(prettier/prettier)


[error] 93-93: Insert ;

(prettier/prettier)


[error] 118-120: Replace ⏎······API_RESPONSES.COHORT_DATA_RESPONSE,⏎····) with API_RESPONSES.COHORT_DATA_RESPONSE);

(prettier/prettier)


[error] 126-126: Delete ,

(prettier/prettier)


[error] 150-152: Replace ⏎········API_RESPONSES.CHILD_DATA,⏎······) with API_RESPONSES.CHILD_DATA);

(prettier/prettier)


[error] 160-160: Delete ,

(prettier/prettier)


[error] 172-173: Delete

(prettier/prettier)


[error] 284-286: Replace ⏎······API_RESPONSES.COHORT_FIELD_DETAILS,⏎····) with API_RESPONSES.COHORT_FIELD_DETAILS);

(prettier/prettier)


[error] 312-312: Insert ;

(prettier/prettier)


[error] 421-423: Replace ⏎········API_RESPONSES.CREATE_COHORT,⏎······) with API_RESPONSES.CREATE_COHORT);

(prettier/prettier)


[error] 436-436: Insert ;

(prettier/prettier)


[error] 553-553: Delete ··

(prettier/prettier)


[error] 554-554: Delete ··

(prettier/prettier)


[error] 566-566: Insert ··

(prettier/prettier)


[error] 567-567: Insert ··

(prettier/prettier)


[error] 568-568: Insert ··

(prettier/prettier)


[error] 608-610: Replace ⏎··········API_RESPONSES.COHORT_UPDATED_SUCCESSFULLY,⏎········) with API_RESPONSES.COHORT_UPDATED_SUCCESSFULLY);

(prettier/prettier)


[error] 632-632: Insert ;

(prettier/prettier)


[error] 915-915: Insert ;

(prettier/prettier)


[error] 973-973: Insert ;

(prettier/prettier)


[error] 1029-1031: Replace ⏎······API_RESPONSES.COHORT_HIERARCHY,⏎····) with API_RESPONSES.COHORT_HIERARCHY);

(prettier/prettier)


[error] 1058-1058: Replace requiredData.userId,·requiredData?.academicYearId with ⏎··········requiredData.userId,⏎··········requiredData?.academicYearId⏎········

(prettier/prettier)


[error] 1102-1102: Insert ;

(prettier/prettier)


[error] 1115-1115: Replace requiredData.userId,·requiredData?.academicYearId with ⏎··········requiredData.userId,⏎··········requiredData?.academicYearId⏎········

(prettier/prettier)


[error] 1165-1165: Insert ;

(prettier/prettier)

src/adapters/postgres/cohortMembers-adapter.ts

[error] 44-44: Delete ·

(prettier/prettier)


[error] 131-131: Insert ;

(prettier/prettier)


[error] 384-384: Insert ;

(prettier/prettier)


[error] 567-567: Insert ;

(prettier/prettier)


[error] 701-701: 'cohortMembershipToUpdate' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 701-701: Insert ⏎········

(prettier/prettier)


[error] 702-702: Replace ········ with ··········

(prettier/prettier)


[error] 703-703: Replace } with ··}⏎······

(prettier/prettier)


[error] 715-715: 'result' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 767-767: Insert ;

(prettier/prettier)


[error] 821-821: Insert ;

(prettier/prettier)


[error] 955-955: Insert ;

(prettier/prettier)


[error] 968-971: Replace ⏎········cohortMembersDto?.cohortId·&&⏎········cohortMembersDto?.cohortId.length·>·0⏎······ with cohortMembersDto?.cohortId·&&·cohortMembersDto?.cohortId.length·>·0

(prettier/prettier)


[error] 1039-1039: Insert ;

(prettier/prettier)

src/adapters/postgres/user-adapter.ts

[error] 89-89: Replace 'OTP_EXPIRY' with "OTP_EXPIRY"

(prettier/prettier)


[error] 90-90: Replace 'OTP_DIGITS' with "OTP_DIGITS"

(prettier/prettier)


[error] 91-91: Replace 'SMS_KEY' with "SMS_KEY"

(prettier/prettier)


[error] 377-377: 'filters' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 377-377: 'exclude' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 377-377: 'sort' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 470-470: Insert ⏎········

(prettier/prettier)


[error] 471-471: Delete ··

(prettier/prettier)


[error] 769-769: Replace ·where:·{·userId:·userDto.userId·} with ⏎········where:·{·userId:·userDto.userId·},⏎·····

(prettier/prettier)


[error] 785-785: Replace userDto.userData.deviceId,·userDto.userId,·user.deviceId) with ⏎············userDto.userData.deviceId,⏎············userDto.userId,⏎············user.deviceId⏎··········);

(prettier/prettier)


[error] 786-787: Delete

(prettier/prettier)


[error] 790-790: Replace userDto.userData.deviceId,·userDto.userId,·user.deviceId) with ⏎············userDto.userData.deviceId,⏎············userDto.userId,⏎············user.deviceId⏎··········);

(prettier/prettier)


[error] 793-794: Delete

(prettier/prettier)


[error] 877-877: Replace userDeviceId:·string,·userId:·string,·existingDeviceId:·string[] with ⏎····userDeviceId:·string,⏎····userId:·string,⏎····existingDeviceId:·string[]⏎··

(prettier/prettier)


[error] 878-878: 'deviceIds' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 892-892: Replace deviceIdforRemove:·string,·userId:·string,·existingDeviceId:·string[] with ⏎····deviceIdforRemove:·string,⏎····userId:·string,⏎····existingDeviceId:·string[]⏎··

(prettier/prettier)


[error] 899-899: Replace id with (id)

(prettier/prettier)


[error] 903-903: Replace userId:·string,·userData:·Partial<User> with ⏎····userId:·string,⏎····userData:·Partial<User>⏎··

(prettier/prettier)


[error] 917-917: Replace ·where:·{·userId·} with ⏎········where:·{·userId·},⏎·····

(prettier/prettier)


[error] 922-922: Replace 'An·error·occurred·while·updating·user·details' with "An·error·occurred·while·updating·user·details"

(prettier/prettier)


[error] 924-926: Delete ⏎⏎

(prettier/prettier)


[error] 986-986: 'errKeycloak' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 1005-1005: 'resKeycloak' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 1005-1006: Replace with ;

(prettier/prettier)


[error] 1008-1008: Replace (resKeycloak.statusCode·!==·201·) with ·(resKeycloak.statusCode·!==·201)·

(prettier/prettier)


[error] 1011-1011: Delete ··

(prettier/prettier)


[error] 1019-1019: Replace else with ·else·

(prettier/prettier)


[error] 1031-1032: Delete

(prettier/prettier)


[error] 1071-1071: Insert ··

(prettier/prettier)


[error] 1072-1072: Insert ··

(prettier/prettier)


[error] 1073-1073: Insert ··

(prettier/prettier)


[error] 1319-1319: Replace user.userId·=·userCreateDto?.userId with (user.userId·=·userCreateDto?.userId)

(prettier/prettier)


[error] 1320-1320: Replace user.username·=·userCreateDto?.username with (user.username·=·userCreateDto?.username)

(prettier/prettier)


[error] 1321-1321: Replace user.firstName·=·userCreateDto?.firstName with (user.firstName·=·userCreateDto?.firstName)

(prettier/prettier)


[error] 1322-1322: Replace user.middleName·=·userCreateDto?.middleName with (user.middleName·=·userCreateDto?.middleName)

(prettier/prettier)


[error] 1323-1323: Replace user.lastName·=·userCreateDto?.lastName with (user.lastName·=·userCreateDto?.lastName)

(prettier/prettier)


[error] 1324-1324: Replace user.gender·=·userCreateDto?.gender with (user.gender·=·userCreateDto?.gender)

(prettier/prettier)


[error] 1325-1325: Replace user.email·=·userCreateDto?.email with (user.email·=·userCreateDto?.email)

(prettier/prettier)


[error] 1326-1326: Replace user.mobile·=·Number(userCreateDto?.mobile)·||·null with (user.mobile·=·Number(userCreateDto?.mobile)·||·null)

(prettier/prettier)


[error] 1327-1327: Replace user.createdBy·=·userCreateDto?.createdBy·||·userCreateDto?.createdBy with (user.createdBy·=·userCreateDto?.createdBy·||·userCreateDto?.createdBy)

(prettier/prettier)


[error] 1338-1338: 'query' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 1340-1340: 'getCohortAcademicYearId' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 1345-1345: 'cohortData' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 1572-1572: Insert ··

(prettier/prettier)


[error] 1679-1679: Insert ··

(prettier/prettier)


[error] 1680-1680: Insert ··

(prettier/prettier)


[error] 1800-1800: Replace mobileOrUsername:·string,·otp:·string,·reason:·string with ⏎····mobileOrUsername:·string,⏎····otp:·string,⏎····reason:·string⏎··

(prettier/prettier)


[error] 1824-1824: Replace mobile,·reason with ⏎········mobile,⏎········reason⏎······

(prettier/prettier)


[error] 1830-1830: Insert ,

(prettier/prettier)


[error] 1832-1832: Insert ,

(prettier/prettier)


[error] 1841-1842: Delete ⏎···

(prettier/prettier)


[error] 1863-1863: Replace mobileWithCode,·otp,·reason with ⏎········mobileWithCode,⏎········otp,⏎········reason⏎······

(prettier/prettier)


[error] 1866-1866: Insert ,

(prettier/prettier)


[error] 1869-1869: Replace "OTP",·"SEND_OTP",·replacements,·[mobile] with ⏎········"OTP",⏎········"SEND_OTP",⏎········replacements,⏎········[mobile]⏎······

(prettier/prettier)


[error] 1871-1872: Delete ⏎···

(prettier/prettier)


[error] 1892-1892: Replace 'signup' with "signup"

(prettier/prettier)


[error] 1903-1903: Replace 'forgot' with "forgot"

(prettier/prettier)


[error] 1923-1923: Replace '.' with "."

(prettier/prettier)


[error] 1980-1980: Replace context:·string,·key:·string,·replacements:·object,·receipients:·string[] with ⏎····context:·string,⏎····key:·string,⏎····replacements:·object,⏎····receipients:·string[]⏎··

(prettier/prettier)


[error] 1997-1997: Replace mailSend?.result?.sms?.errors·&&·mailSend.result.sms.errors.length·>·0 with ⏎········mailSend?.result?.sms?.errors·&&⏎········mailSend.result.sms.errors.length·>·0⏎······

(prettier/prettier)


[error] 1998-1998: Replace (error:·{·error:·string;·})·=>·error.error with ⏎··········(error:·{·error:·string·})·=>·error.error⏎········

(prettier/prettier)


[error] 2003-2004: Delete ⏎···

(prettier/prettier)


[error] 2006-2006: Replace ${API_RESPONSES.SMS_NOTIFICATION_ERROR}:··${error.message} with ⏎········${API_RESPONSES.SMS_NOTIFICATION_ERROR}:··${error.message}⏎······

(prettier/prettier)


[error] 2011-2011: Replace body:·SendPasswordResetOTPDto,·response:·Response with ⏎····body:·SendPasswordResetOTPDto,⏎····response:·Response⏎··

(prettier/prettier)


[error] 2015-2015: 'error' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 2016-2016: 'success' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 2037-2037: Replace '' with ""

(prettier/prettier)


[error] 2040-2040: Replace username,·otp,·reason with ⏎········username,⏎········otp,⏎········reason⏎······

(prettier/prettier)


[error] 2044-2044: Insert ,

(prettier/prettier)


[error] 2047-2047: Replace userData.mobile with ⏎············userData.mobile,⏎··········

(prettier/prettier)


[error] 2048-2048: Replace 'SMS' with "SMS"

(prettier/prettier)


[error] 2050-2050: Replace ·type:·'SMS',·message:·${API_RESPONSES.MOBILE_OTP_SEND_FAILED}·${e.message}·}) with ⏎············type:·"SMS",⏎············message:·${API_RESPONSES.MOBILE_OTP_SEND_FAILED}·${e.message},⏎··········});

(prettier/prettier)


[error] 2058-2058: Insert ,

(prettier/prettier)


[error] 2061-2061: Replace userData.email with ⏎············userData.email,⏎··········

(prettier/prettier)


[error] 2062-2062: Replace ·type:·'Email',·message:·API_RESPONSES.EMAIL_SENT_OTP·}) with ⏎············type:·"Email",⏎············message:·API_RESPONSES.EMAIL_SENT_OTP,⏎··········});

(prettier/prettier)


[error] 2064-2064: Replace ·type:·'Email',·message:·${API_RESPONSES.EMAIL_OTP_SEND_FAILED}:·${e.message}·}) with ⏎············type:·"Email",⏎············message:·${API_RESPONSES.EMAIL_OTP_SEND_FAILED}:·${e.message},⏎··········});

(prettier/prettier)


[error] 2067-2067: Delete ·

(prettier/prettier)


[error] 2068-2068: Insert ⏎·······

(prettier/prettier)


[error] 2069-2069: Replace '' with ""

(prettier/prettier)


[error] 2070-2070: Replace e·=>·e.type·===·'SMS' with (e)·=>·e.type·===·"SMS"

(prettier/prettier)


[error] 2071-2071: Replace .filter(e·=>·e.type·===·'SMS').map(e·=>·e.message) with ⏎············.filter((e)·=>·e.type·===·"SMS")⏎············.map((e)·=>·e.message)⏎············

(prettier/prettier)


[error] 2073-2073: Replace e·=>·e.type·===·'Email' with (e)·=>·e.type·===·"Email"

(prettier/prettier)


[error] 2074-2074: Replace .filter(e·=>·e.type·===·'Email').map(e·=>·e.message) with ⏎············.filter((e)·=>·e.type·===·"Email")⏎············.map((e)·=>·e.message)⏎············

(prettier/prettier)


[error] 2088-2088: Insert ,

(prettier/prettier)


[error] 2089-2089: Insert ;

(prettier/prettier)


[error] 2097-2098: Delete ⏎···

(prettier/prettier)


[error] 2107-2108: Delete

(prettier/prettier)


[error] 2111-2111: Replace context:·string,·key:·string,·replacements:·object,·emailReceipt with ⏎····context:·string,⏎····key:·string,⏎····replacements:·object,⏎····emailReceipt⏎··

(prettier/prettier)


[error] 2126-2126: Replace mailSend?.result?.email?.errors·&&·mailSend.result.email.errors.length·>·0 with ⏎········mailSend?.result?.email?.errors·&&⏎········mailSend.result.email.errors.length·>·0⏎······

(prettier/prettier)


[error] 2127-2127: Replace (error:·{·error:·string;·})·=>·error.error with ⏎··········(error:·{·error:·string·})·=>·error.error⏎········

(prettier/prettier)


[error] 2132-2133: Delete ⏎···

(prettier/prettier)


[error] 2135-2135: Replace ${API_RESPONSES.EMAIL_NOTIFICATION_ERROR}:··${e.message} with ⏎········${API_RESPONSES.EMAIL_NOTIFICATION_ERROR}:··${e.message}⏎······

(prettier/prettier)


[error] 2137-2138: Delete

(prettier/prettier)

🪛 GitHub Check: SonarCloud
manifest/backend.yaml

[warning] 31-31: Memory limits should be enforced

Specify a memory limit for this container.

See more on SonarQube Cloud

🪛 yamllint (1.35.1)
.github/workflows/tekdi-server-deployment.yaml

[warning] 7-7: wrong indentation: expected 2 but found 3

(indentation)


[warning] 8-8: wrong indentation: expected 5 but found 4

(indentation)


[warning] 11-11: wrong indentation: expected 6 but found 4

(indentation)


[error] 11-11: trailing spaces

(trailing-spaces)


[warning] 15-15: wrong indentation: expected 8 but found 10

(indentation)


[error] 19-19: trailing spaces

(trailing-spaces)

.github/workflows/dev-pratham-eks-deployment.yaml

[error] 20-20: trailing spaces

(trailing-spaces)


[error] 34-34: trailing spaces

(trailing-spaces)


[error] 36-36: trailing spaces

(trailing-spaces)

🪛 Biome (1.9.4)
src/adapters/postgres/rbac/privilegerole.adapter.ts

[error] 87-87: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)

src/adapters/postgres/fields-adapter.ts

[error] 438-438: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 575-575: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 1434-1434: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 1752-1752: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 1753-1753: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

src/cohort/dto/cohort-search.dto.ts

[error] 137-137: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

src/adapters/postgres/cohort-adapter.ts

[error] 274-274: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 275-275: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 528-528: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)


[error] 566-566: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

src/adapters/postgres/cohortMembers-adapter.ts

[error] 725-725: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

src/adapters/postgres/user-adapter.ts

[error] 566-566: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 599-599: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 681-681: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 1185-1185: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)


[error] 1071-1071: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


[error] 1677-1677: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1924-1924: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (12)
src/authRbac/authRbac.module.ts (1)

7-7: LGTM! Path correction for PostgresModule import.

The import path has been correctly updated, fixing the typo from 'potsgres-module' to 'postgres-module'.

src/auth/auth.controller.ts (1)

47-47: LGTM! The login implementation follows NestJS best practices.

The method correctly handles authentication with proper validation and error handling.

src/cohort/cohort.controller.ts (1)

58-58: Verify the impact of changing the route path

Changing the route from /read/:cohortId to /cohortHierarchy/:cohortId is a breaking change. Ensure that all clients consuming this API are updated to use the new endpoint to prevent any disruptions.

src/academicyears/academicyears.module.ts (1)

1-14: LGTM! Module structure follows NestJS best practices.

The module is well-structured with proper dependency injection and follows NestJS naming conventions.

🧰 Tools
🪛 eslint

[error] 14-14: Delete ·

(prettier/prettier)

src/auth/auth.module.ts (1)

10-11: LGTM! Module updates follow NestJS best practices.

The changes improve the module structure by:

  1. Using absolute import paths
  2. Updating entity references
  3. Removing unused dependencies

Also applies to: 14-14, 18-18

src/authRbac/authRbac.controller.ts (1)

31-38: Verify the impact of using @res() decorator.

Using @Res() decorator in NestJS bypasses the standard response handling. Ensure this aligns with the application's error handling strategy.

✅ Verification successful

@res() decorator usage aligns with application's error handling strategy

The @res() decorator usage in signInRbac is consistent with the codebase's architectural pattern. The application implements proper global exception handling through AllExceptionsFilter and uses a standardized APIResponse format across all controllers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for consistent response handling patterns
rg -l "@Res\(\)" | xargs -I {} rg "APIResponse" {} -C 2

Length of output: 365


Script:

#!/bin/bash
# Check for @Res decorator usage
rg "@Res\(\)" -B 2 -A 2

# Check for authService implementation
ast-grep --pattern 'class AuthService {
  $$$
  signInRbac($$$) {
    $$$
  }
  $$$
}'

# Check for exception filters and interceptors
fd "\.filter\.|\.interceptor\." --exec rg -l "implements"

Length of output: 23890


Script:

#!/bin/bash
# Check exception filter implementation
cat src/common/filters/exception.filter.ts

# Look for APIResponse implementation
rg -l "class APIResponse" 

Length of output: 1214

src/app.module.ts (1)

42-45: LGTM! Well-organized module structure.

The new modules are properly organized and follow NestJS best practices. The separation of concerns between Forms, Tenant, AcademicYears, and CohortAcademicYear is clear and maintainable.

src/cohort/cohort.module.ts (1)

43-51: LGTM! Well-structured provider organization.

The providers are properly organized and follow NestJS dependency injection patterns. The services are clearly separated by responsibility.

src/adapters/postgres/rbac/privilege-adapter.ts (1)

285-297: ⚠️ Potential issue

Use parameterized query for privilege search.

The SQL query in getPrivilegebyRoleId uses string concatenation which could be vulnerable to SQL injection.

-      const query = `SELECT r.*, u.*
-        FROM public."RolePrivilegesMapping" AS r
-        inner JOIN public."Privileges" AS u ON r."privilegeId" = u."privilegeId"
-        where r."roleId"=$1`;
+      const query = await this.rolePrivilegeMappingRepository
+        .createQueryBuilder('r')
+        .select(['r.*', 'u.*'])
+        .innerJoin('Privileges', 'u', 'r.privilegeId = u.privilegeId')
+        .where('r.roleId = :roleId', { roleId })
+        .getRawMany();

Likely invalid or redundant comment.

.github/workflows/tekdi-server-deployment.yaml (1)

19-26: Verify the existence and permissions of deploy.sh script.

The workflow directly executes deploy.sh without checking if it exists or has proper execution permissions. This could cause deployment failures.

🧰 Tools
🪛 yamllint (1.35.1)

[error] 19-19: trailing spaces

(trailing-spaces)

.coderabbit.yaml (1)

31-31: LGTM! Addition of 'main' branch is appropriate.

This change aligns with standard Git workflow practices where 'main' is commonly used as the default branch.

package.json (1)

40-41: Verify CSV parsing security measures.

The addition of csv and csvtojson packages requires careful handling to prevent CSV injection attacks.

Comment on lines +60 to +61
const tenantId = request?.headers["tenantid"];
return this.authService.getUserByAuth(request, tenantId, response);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve header extraction and validation.

Consider these improvements:

  1. Use NestJS's @Headers() decorator for cleaner header extraction
  2. Add validation for required tenantId
  3. Use consistent header casing (conventional is 'TenantId')
-  public async getUserByAuth(@Req() request, @Res() response: Response) {
-    const tenantId = request?.headers["tenantid"];
-    return this.authService.getUserByAuth(request, tenantId, response);
+  public async getUserByAuth(
+    @Req() request,
+    @Headers('TenantId') tenantId: string,
+    @Res() response: Response
+  ) {
+    if (!tenantId) {
+      throw new BadRequestException('TenantId header is required');
+    }
+    return this.authService.getUserByAuth(request, tenantId, response);
📝 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 tenantId = request?.headers["tenantid"];
return this.authService.getUserByAuth(request, tenantId, response);
public async getUserByAuth(
@Req() request,
@Headers('TenantId') tenantId: string,
@Res() response: Response
) {
if (!tenantId) {
throw new BadRequestException('TenantId header is required');
}
return this.authService.getUserByAuth(request, tenantId, response);
}


@ApiTags("Academicyears")
@Controller("academicyears")
@UseGuards(JwtAuthGuard)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update method name for consistency

The method name createAcademicYears suggests it handles multiple records, but it processes a single academic year. Rename it to createAcademicYear for clarity and consistency with RESTful conventions.

Apply this diff:

 export class AcademicyearsController {
-  async createAcademicYears(
+  async createAcademicYear(

Committable suggestion skipped: line range outside the PR's diff.

@ApiCreatedResponse({ description: API_RESPONSES.ACADEMICYEAR })
@ApiHeader({ name: "tenantid" })
async createAcademicYears(
@Body() academicyearsService: AcademicYearDto,
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Rename parameter to academicYearDto for clarity

The parameter name academicyearsService is misleading since it suggests a service rather than a data transfer object. For consistency and clarity, it should be renamed to academicYearDto.

Apply this diff to rename the parameter:

-    @Body() academicyearsService: AcademicYearDto,
+    @Body() academicYearDto: AcademicYearDto,

And update its usage within the method:

-        .createAcademicYear(academicyearsService, tenantId, response);
+        .createAcademicYear(academicYearDto, tenantId, response);
📝 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
@Body() academicyearsService: AcademicYearDto,
@Body() academicYearDto: AcademicYearDto,

Comment on lines +130 to +134
async isCohortExistForYear(yearId, cohortId) {
return await this.cohortAcademicYearRepository.find({
where: { academicYearId: yearId, cohortId: cohortId },
});
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type annotations to method parameters

The method isCohortExistForYear lacks explicit type annotations for yearId and cohortId. Adding types enhances code clarity and type safety.

Apply this diff:

-  async isCohortExistForYear(yearId, cohortId) {
+  async isCohortExistForYear(yearId: string, cohortId: string) {
📝 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
async isCohortExistForYear(yearId, cohortId) {
return await this.cohortAcademicYearRepository.find({
where: { academicYearId: yearId, cohortId: cohortId },
});
}
async isCohortExistForYear(yearId: string, cohortId: string) {
return await this.cohortAcademicYearRepository.find({
where: { academicYearId: yearId, cohortId: cohortId },
});
}

Comment on lines +170 to +199
const apiId = APIID.ACADEMICYEAR_GET;
try {
const academicYearResult = await this.academicYearRespository.findOne({ where: { id: id } });
if (!academicYearResult) {
return APIResponse.error(
response,
apiId,
API_RESPONSES.ACADEMICYEAR_NOTFOUND,
API_RESPONSES.NOT_FOUND,
HttpStatus.BAD_REQUEST
);
}
return APIResponse.success(
response,
apiId,
academicYearResult,
HttpStatus.OK,
API_RESPONSES.ACADEMICYEAR_GET_SUCCESS
);
} catch (error) {
const errorMessage = error.message || API_RESPONSES.INTERNAL_SERVER_ERROR;
return APIResponse.error(
response,
apiId,
API_RESPONSES.INTERNAL_SERVER_ERROR,
errorMessage,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type annotations to method parameters

The method getAcademicYearById lacks explicit type annotations for id and response. Including these enhances type safety and code readability.

Apply this diff:

-  async getAcademicYearById(id, response) {
+  async getAcademicYearById(id: string, response: Response) {

Ensure that Response is imported from "express" if not already imported.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 eslint

[error] 172-172: Replace ·where:·{·id:·id·} with ⏎········where:·{·id:·id·},⏎·····

(prettier/prettier)

Comment on lines +110 to +126
@ApiPropertyOptional({
type: String,
description: "State",
})
states: string;

@ApiPropertyOptional({
type: String,
description: "District",
})
districts: string;

@ApiPropertyOptional({
type: String,
description: "Block",
})
blocks: string;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation decorators for location fields.

The location fields (states, districts, blocks) lack proper validation decorators.

Apply this diff:

   @ApiPropertyOptional({
     type: String,
     description: "State",
   })
+  @IsOptional()
+  @IsString()
+  @IsNotEmpty()
   states: string;

   @ApiPropertyOptional({
     type: String,
     description: "District",
   })
+  @IsOptional()
+  @IsString()
+  @IsNotEmpty()
   districts: string;

   @ApiPropertyOptional({
     type: String,
     description: "Block",
   })
+  @IsOptional()
+  @IsString()
+  @IsNotEmpty()
   blocks: string;
📝 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
@ApiPropertyOptional({
type: String,
description: "State",
})
states: string;
@ApiPropertyOptional({
type: String,
description: "District",
})
districts: string;
@ApiPropertyOptional({
type: String,
description: "Block",
})
blocks: string;
@ApiPropertyOptional({
type: String,
description: "State",
})
@IsOptional()
@IsString()
@IsNotEmpty()
states: string;
@ApiPropertyOptional({
type: String,
description: "District",
})
@IsOptional()
@IsString()
@IsNotEmpty()
districts: string;
@ApiPropertyOptional({
type: String,
description: "Block",
})
@IsOptional()
@IsString()
@IsNotEmpty()
blocks: string;

Comment on lines +71 to +95
public async getUserByAuth(request: any, tenantId, response: Response) {
const apiId = APIID.USER_AUTH;
try {
const decoded: any = jwt_decode(request.headers.authorization);
const username = decoded.preferred_username;
const data = await this.useradapter.buildUserAdapter().findUserDetails(null, username);
const data = await this.useradapter
.buildUserAdapter()
.findUserDetails(null, username, tenantId);

return APIResponse.success(response, apiId, data,
HttpStatus.OK, "User fetched by auth token Successfully.")
return APIResponse.success(
response,
apiId,
data,
HttpStatus.OK,
"User fetched by auth token Successfully."
);
} catch (e) {
const errorMessage = e?.message || 'Something went wrong';
return APIResponse.error(response, apiId, "Internal Server Error", `Error : ${errorMessage}`, HttpStatus.INTERNAL_SERVER_ERROR)
const errorMessage = e?.message || "Something went wrong";
return APIResponse.error(
response,
apiId,
"Internal Server Error",
`Error : ${errorMessage}`,
HttpStatus.INTERNAL_SERVER_ERROR
);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error type handling for JWT decode failures.

The getUserByAuth method uses jwt_decode without proper error handling. If the token is malformed, it could throw an error that isn't properly caught.

 public async getUserByAuth(request: any, tenantId, response: Response) {
   const apiId = APIID.USER_AUTH;
   try {
-    const decoded: any = jwt_decode(request.headers.authorization);
+    let decoded: any;
+    try {
+      decoded = jwt_decode(request.headers.authorization);
+    } catch (error) {
+      return APIResponse.error(
+        response,
+        apiId,
+        "Invalid Token",
+        "Failed to decode JWT token",
+        HttpStatus.UNAUTHORIZED
+      );
+    }
     const username = decoded.preferred_username;
📝 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
public async getUserByAuth(request: any, tenantId, response: Response) {
const apiId = APIID.USER_AUTH;
try {
const decoded: any = jwt_decode(request.headers.authorization);
const username = decoded.preferred_username;
const data = await this.useradapter.buildUserAdapter().findUserDetails(null, username);
const data = await this.useradapter
.buildUserAdapter()
.findUserDetails(null, username, tenantId);
return APIResponse.success(response, apiId, data,
HttpStatus.OK, "User fetched by auth token Successfully.")
return APIResponse.success(
response,
apiId,
data,
HttpStatus.OK,
"User fetched by auth token Successfully."
);
} catch (e) {
const errorMessage = e?.message || 'Something went wrong';
return APIResponse.error(response, apiId, "Internal Server Error", `Error : ${errorMessage}`, HttpStatus.INTERNAL_SERVER_ERROR)
const errorMessage = e?.message || "Something went wrong";
return APIResponse.error(
response,
apiId,
"Internal Server Error",
`Error : ${errorMessage}`,
HttpStatus.INTERNAL_SERVER_ERROR
);
public async getUserByAuth(request: any, tenantId, response: Response) {
const apiId = APIID.USER_AUTH;
try {
let decoded: any;
try {
decoded = jwt_decode(request.headers.authorization);
} catch (error) {
return APIResponse.error(
response,
apiId,
"Invalid Token",
"Failed to decode JWT token",
HttpStatus.UNAUTHORIZED
);
}
const username = decoded.preferred_username;
const data = await this.useradapter
.buildUserAdapter()
.findUserDetails(null, username, tenantId);
return APIResponse.success(
response,
apiId,
data,
HttpStatus.OK,
"User fetched by auth token Successfully."
);
} catch (e) {
const errorMessage = e?.message || "Something went wrong";
return APIResponse.error(
response,
apiId,
"Internal Server Error",
`Error : ${errorMessage}`,
HttpStatus.INTERNAL_SERVER_ERROR
);

Comment on lines +17 to +53
public async createPrivilegeRole(
request: Request,
createPrivilegeRoleDto: CreatePrivilegeRoleDto,
response: Response
) {
const apiId = APIID.ASSIGNPRIVILEGE_CREATE;
try {
let result ;
if (createPrivilegeRoleDto.deleteOld) {
await this.deleteByRoleId(createPrivilegeRoleDto.roleId);
}
const privilegeRoles = createPrivilegeRoleDto.privilegeId.map(privilegeId => ({
let result;
if (createPrivilegeRoleDto.deleteOld) {
await this.deleteByRoleId(createPrivilegeRoleDto.roleId);
}
const privilegeRoles = createPrivilegeRoleDto.privilegeId.map(
(privilegeId) => ({
roleId: createPrivilegeRoleDto.roleId,
tenantId: createPrivilegeRoleDto.tenantId,
privilegeId,
})
);
const existingPrivileges = await this.rolePrivilegeMappingRepository.find(
{
where: {
roleId: createPrivilegeRoleDto.roleId,
privilegeId
}));
const existingPrivileges = await this.rolePrivilegeMappingRepository.find({
where: {
roleId: createPrivilegeRoleDto.roleId,
privilegeId: In(createPrivilegeRoleDto.privilegeId)
}
});
tenantId: createPrivilegeRoleDto.tenantId,
privilegeId: In(createPrivilegeRoleDto.privilegeId),
},
}
);

const newPrivileges = privilegeRoles.filter(privilegeRole => {
return !existingPrivileges.some(existing => existing.privilegeId === privilegeRole.privilegeId);
});
const newPrivileges = privilegeRoles.filter((privilegeRole) => {
return !existingPrivileges.some(
(existing) => existing.privilegeId === privilegeRole.privilegeId
);
});

for (let data of newPrivileges) {
result = await this.rolePrivilegeMappingRepository.save(data);
}
for (const data of newPrivileges) {
result = await this.rolePrivilegeMappingRepository.save(data);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add transaction handling for privilege assignments.

The createPrivilegeRole method performs multiple database operations without transaction handling.

 public async createPrivilegeRole(
   request: Request,
   createPrivilegeRoleDto: CreatePrivilegeRoleDto,
   response: Response
 ) {
   const apiId = APIID.ASSIGNPRIVILEGE_CREATE;
   try {
+    return await this.rolePrivilegeMappingRepository.manager.transaction(async transactionalEntityManager => {
       let result;
       if (createPrivilegeRoleDto.deleteOld) {
-        await this.deleteByRoleId(createPrivilegeRoleDto.roleId);
+        await transactionalEntityManager.delete(RolePrivilegeMapping, { roleId: createPrivilegeRoleDto.roleId });
       }
       // ... rest of the code
+    });
   } catch (error) {
     // ... error handling
   }
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +194 to +272
if (
whereClause.userId &&
whereClause.tenantId &&
whereClause.field === "Privilege"
) {
const userRoleMappingData = await this.findUserRoleData(
whereClause.userId,
whereClause.tenantId
);
const roleIds = userRoleMappingData.map((data) => data.roleid);

const result = await this.findPrivilegeByRoleId(roleIds);

const roles = userRoleMappingData.map(data => {
const roleResult = result.find(privilegeData => privilegeData.roleid === data.roleid);
const roles = userRoleMappingData.map((data) => {
const roleResult = result.find(
(privilegeData) => privilegeData.roleid === data.roleid
);
return {
roleId: data.roleid,
title: data.title,
code: data.code,
privileges: roleResult ? roleResult : []
privileges: roleResult ? roleResult : [],
};
});
return APIResponse.success(response, apiId, roles, HttpStatus.OK, 'Role For User with Privileges fetched successfully.')
} else if (whereClause.userId && whereClause.tenantId && !whereClause.field) {
const data = await this.findUserRoleData(whereClause.userId, whereClause.tenantId)
return APIResponse.success(response, apiId, data, HttpStatus.OK, 'Role For User Id fetched successfully.')
}
else if (whereClause.tenantId && whereClause.field === "Privilege") {
return APIResponse.success(
response,
apiId,
roles,
HttpStatus.OK,
"Role For User with Privileges fetched successfully."
);
} else if (
whereClause.userId &&
whereClause.tenantId &&
!whereClause.field
) {
const data = await this.findUserRoleData(
whereClause.userId,
whereClause.tenantId
);
return APIResponse.success(
response,
apiId,
data,
HttpStatus.OK,
"Role For User Id fetched successfully."
);
} else if (whereClause.tenantId && whereClause.field === "Privilege") {
const userRoleData = await this.findRoleData(whereClause.tenantId);
const result = await this.findPrivilegeByRoleId(userRoleData.map(data => data.roleId));
const roles = userRoleData.map(data => {
const roleResult = result.find(privilegeData => privilegeData.roleid === data.roleId);
const result = await this.findPrivilegeByRoleId(
userRoleData.map((data) => data.roleId)
);
const roles = userRoleData.map((data) => {
const roleResult = result.find(
(privilegeData) => privilegeData.roleid === data.roleId
);
return {
roleId: data.roleId,
title: data.title,
code: data.code,
privileges: roleResult ? roleResult : []
privileges: roleResult ? roleResult : [],
};
});
return APIResponse.success(response, apiId, roles, HttpStatus.OK, 'Role For Tenant with Privileges fetched successfully.')
return APIResponse.success(
response,
apiId,
roles,
HttpStatus.OK,
"Role For Tenant with Privileges fetched successfully."
);
} else if (whereClause.tenantId && !whereClause.field) {
const data = await this.findRoleData(whereClause.tenantId);
return APIResponse.success(response, apiId, data, HttpStatus.OK, 'Role For Tenant fetched successfully.')
return APIResponse.success(
response,
apiId,
data,
HttpStatus.OK,
"Role For Tenant fetched successfully."
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor complex search conditions.

The search logic contains duplicated code and complex nested conditions. Consider extracting the search strategies into separate methods.

private async searchByUserWithPrivileges(userId: string, tenantId: string) {
  const userRoleMappingData = await this.findUserRoleData(userId, tenantId);
  const roleIds = userRoleMappingData.map((data) => data.roleid);
  const result = await this.findPrivilegeByRoleId(roleIds);
  return this.mapRolesWithPrivileges(userRoleMappingData, result);
}

private mapRolesWithPrivileges(roleData: any[], privileges: any[]) {
  return roleData.map((data) => ({
    roleId: data.roleid || data.roleId,
    title: data.title,
    code: data.code,
    privileges: privileges.find((p) => p.roleid === (data.roleid || data.roleId)) || []
  }));
}

@@ -28,6 +28,15 @@
- configMapRef:
name: backend-service-config
resources: {}
- name: cloudwatch-logs-agent
image: amazon/aws-for-fluent-bit:latest
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using 'latest' tag for container images.

Using latest tag for aws-for-fluent-bit is risky as it can lead to unexpected behavior with automatic updates. Specify a fixed version.

-        image: amazon/aws-for-fluent-bit:latest
+        image: amazon/aws-for-fluent-bit:2.31.12
📝 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
image: amazon/aws-for-fluent-bit:latest
image: amazon/aws-for-fluent-bit:2.31.12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants