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

PS-1243 Master data management #249

Open
wants to merge 2 commits into
base: Shiksha-2.0
Choose a base branch
from

Conversation

Sourav-Tekdi
Copy link
Collaborator

@Sourav-Tekdi Sourav-Tekdi commented Jul 16, 2024

Summary by CodeRabbit

  • New Features

    • Introduced updateFields functionality for updating field details through the API.
    • Expanded FieldsDto and FieldsUpdateDto for detailed field attributes and context.
  • Bug Fixes

    • Improved error handling and response structure in field update processes.
  • Improvements

    • Enhanced field data validation and documentation.
    • Updated logic for field data fetching and dependency management.
    • Refined field attributes and context handling for better consistency and clarity.

Copy link

coderabbitai bot commented Jul 16, 2024

Walkthrough

The recent updates introduce significant changes across multiple files, focusing on enhancing field management capabilities. Key additions include the updateFields method across various service layers and a FieldsUpdateDto data transfer object for updating field details. Several methods were updated or commented out for handling field rendering, error handling, and improving the overall logic for field operations such as creation, fetching, and updating.

Changes

File Path Change Summary
src/adapters/fieldsservicelocator.ts Added updateFields method to the IServicelocatorfields interface.
src/adapters/hasura/services/fields.service.ts Commented out rendering logic in addRender method.
src/adapters/postgres/fields-adapter.ts Added FieldsUpdateDto import and updated error handling, response structure, and methods for field creation and updating.
src/fields/dto/fields-update.dto.ts Introduced FieldsUpdateDto with properties for updating fields, including validation and Swagger API documentation annotations.
src/fields/dto/fields.dto.ts Modified FieldsDto by adding new properties like contextType, tenantId, and removing several older properties.
src/fields/entities/fields.entity.ts Updated column types and annotations, including changing dependsOn from boolean to varchar.
src/fields/fields.controller.ts Added updateFields method to handle PATCH requests for updating fields.
src/fields/fields.service.ts Added updateFields method and adjusted typings for several parameters in existing methods.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 10

Outside diff range, codebase verification and nitpick comments (1)
src/fields/dto/fields.dto.ts (1)

36-43: Refine the context property definition.

The context property has been updated with a new description and default value. Ensure that the new definition aligns with the intended use of the property within the application. If context is a critical field, consider removing the default empty string, as it might mask missing data issues.

- @ApiPropertyOptional({ type: String, description: "The context of the fields", default: "" })
+ @ApiPropertyOptional({ type: String, description: "The specific context in which the fields are used" })
Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3385627 and 56401f9.

Files selected for processing (8)
  • src/adapters/fieldsservicelocator.ts (1 hunks)
  • src/adapters/hasura/services/fields.service.ts (3 hunks)
  • src/adapters/postgres/fields-adapter.ts (8 hunks)
  • src/fields/dto/fields-update.dto.ts (1 hunks)
  • src/fields/dto/fields.dto.ts (4 hunks)
  • src/fields/entities/fields.entity.ts (3 hunks)
  • src/fields/fields.controller.ts (2 hunks)
  • src/fields/fields.service.ts (8 hunks)
Additional context used
Path-based instructions (8)
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/fields/dto/fields.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/fields/entities/fields.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/fields/dto/fields-update.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/fields/fields.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/fields/fields.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/adapters/hasura/services/fields.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/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."
Biome
src/fields/dto/fields-update.dto.ts

[error] 70-70: Don't use 'Number' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'number' instead

(lint/complexity/noBannedTypes)

src/adapters/postgres/fields-adapter.ts

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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

Additional comments not posted (9)
src/fields/dto/fields.dto.ts (1)

73-90: Verify new properties for consistency and relevance.

New properties like tenantId, fieldParams, and fieldAttributes have been added. Ensure these additions are consistent with the application's data model and are used appropriately in the business logic. Also, verify that the default: {} for fieldParams and fieldAttributes is intentional, as this might introduce empty objects where null values might be more appropriate.

src/fields/entities/fields.entity.ts (1)

54-54: Check the note property for consistency.

The note property has been adjusted for whitespace. Ensure this change is consistent with the coding standards and does not affect the database schema or the application's functionality.

src/fields/fields.service.ts (4)

87-104: Query Handling Improvements

The updates to the searchFieldData method, including parsing the limit as an integer and dynamically adjusting the query options, enhance the robustness and flexibility of field data fetching. These changes are well-implemented.


Line range hint 139-160: Consistent Query Handling

The searchFieldValues method follows a consistent pattern with searchFieldData, effectively handling dynamic query options. The integration of getSearchFieldValueData for actual data fetching is a good example of modular code design.


160-176: Efficient Data Fetching

The getSearchFieldValueData method effectively handles pagination and query options, ensuring efficient data fetching. The structure and logic of the method are clear and align with best practices for scalable applications.


180-186: Specific Data Fetching

The searchFieldValueId method is implemented correctly to fetch specific field values based on cohortId and fieldId. The use of query parameters is appropriate and follows best practices for data retrieval.

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

19-19: Addition of FieldsUpdateDto import.

The import of FieldsUpdateDto is a new addition, likely used in the updated updateFields method.

This change is straightforward and aligns with the updates made in the updateFields method.


89-95: Enhanced error handling in getFormCustomField.

The method now handles exceptions more robustly, providing specific HTTP status codes and error messages.

The use of HttpStatus.INTERNAL_SERVER_ERROR and a more descriptive error message improves the error handling capabilities of this method.


193-210: Check for existing fields before creation.

This new logic prevents the creation of duplicate fields based on context and name, which enhances data integrity.

The use of HttpStatus.CONFLICT is appropriate for handling duplicate entries. Ensure that the front-end handles this response correctly.

export interface IServicelocatorfields {
//fields
createFields(request: any, fieldsDto: FieldsDto, response: Response);
//Update
updateFields(fieldId: any, request: any, fieldsUpdateDto: FieldsUpdateDto, response: Response);
Copy link

Choose a reason for hiding this comment

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

Ensure parameter typing and error handling in updateFields.

The method updateFields uses any type for several parameters. Using any can lead to potential bugs due to lack of type safety. Consider specifying more precise types, especially if they can be derived from other parts of the application.

Additionally, there's no error handling or return type specified. It's good practice, especially in TypeScript, to define what a function returns for better predictability and maintainability.

- updateFields(fieldId: any, request: any, fieldsUpdateDto: FieldsUpdateDto, response: Response);
+ updateFields(fieldId: string, request: Request, fieldsUpdateDto: FieldsUpdateDto, response: Response): Promise<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
updateFields(fieldId: any, request: any, fieldsUpdateDto: FieldsUpdateDto, response: Response);
updateFields(fieldId: string, request: Request, fieldsUpdateDto: FieldsUpdateDto, response: Response): Promise<Response>;

@Column({ type: 'boolean' })
dependsOn: boolean;
@Column({ type: 'varchar' })
dependsOn: string;
Copy link

Choose a reason for hiding this comment

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

Adjust the dependsOn property type change.

The dependsOn property type has been changed from boolean to varchar. This is a significant change that may affect how data is handled in the application. Ensure that all references to this property have been updated to reflect the new type, and consider adding a migration script if the database schema is affected.

- @Column({ type: 'boolean' }) dependsOn: boolean;
+ @Column({ type: 'varchar' }) dependsOn: 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
dependsOn: string;
@Column({ type: 'varchar' }) dependsOn: string;

default: 0,
})
@Expose()
ordering: Number;
Copy link

Choose a reason for hiding this comment

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

Correct the primitive type for ordering.

The ordering property incorrectly uses Number as its type. According to TypeScript best practices and the static analysis hint, it should use the lowercase number for primitive types.

- ordering: Number;
+ ordering: number;
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
ordering: Number;
ordering: number;
Tools
Biome

[error] 70-70: Don't use 'Number' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'number' instead

(lint/complexity/noBannedTypes)

@@ -56,22 +56,23 @@ export class FieldsService {
});
}
}
async updateFields(request: any, fieldsDto: FieldsDto) { }
Copy link

Choose a reason for hiding this comment

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

Empty Method Implementation

The updateFields method is currently empty. If this is intentional (e.g., a placeholder for future implementation), consider adding a TODO comment or documentation explaining the reason. If it's an oversight, the method needs an implementation.

@@ -207,7 +208,7 @@ export class FieldsService {
}
}

public async getFieldsAndFieldsValues(cohortId:string){
public async getFieldsAndFieldsValues(cohortId: string) {
Copy link

Choose a reason for hiding this comment

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

Use of Raw SQL

The getFieldsAndFieldsValues method uses a raw SQL query. If this is due to complex joins or database-specific features, consider adding a comment to explain why raw SQL is used instead of ORM methods. Additionally, ensure that parameters are safely bound to prevent SQL injection.

- let query = `SELECT FV."value",FV."itemId", FV."fieldId", F."name" AS fieldname, F."label", F."context",F."type", F."state", F."contextType", F."fieldParams" FROM public."FieldValues" FV 
+ let query = `SELECT FV."value",FV."itemId", FV."fieldId", F."name" AS fieldname, F."label", F."context",F."type", F."state", F."contextType", F."fieldParams" FROM public."FieldValues" FV 
  LEFT JOIN public."Fields" F
  ON FV."fieldId" = F."fieldId" where FV."itemId" =$1`;

Committable suggestion was skipped due to low confidence.

Comment on lines +18 to +19
// //add render json object
// fieldsDto = await this.addRender(fieldsDto);
Copy link

Choose a reason for hiding this comment

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

Temporary removal of rendering functionality needs clarification.

The addRender call has been commented out in the createFields method. This might affect the functionality depending on how the FieldsDto is expected to handle rendering.

Please provide context or documentation on why this functionality is temporarily disabled and the expected impact on the system.

Comment on lines +315 to +316
// //add render json object
// fieldsDto = await this.addRender(fieldsDto);
Copy link

Choose a reason for hiding this comment

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

Temporary removal of rendering functionality needs clarification.

Similar to the createFields method, the addRender call has been commented out in the updateFields method.

Ensure that all dependent functionalities are reviewed and adjusted accordingly to handle this change.

Comment on lines +367 to +375
// public async addRender(fieldsDto: FieldsDto) {
// let fieldsDtoTemp = fieldsDto;
// if (fieldsDtoTemp?.render) {
// let renderObj = await this.createFieldSchema(fieldsDtoTemp?.render);
// fieldsDtoTemp.render = JSON.stringify(JSON.stringify(renderObj));
// }
// fieldsDto = fieldsDtoTemp;
// return fieldsDto;
// }
Copy link

Choose a reason for hiding this comment

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

Commented out addRender method.

The entire addRender method has been commented out, which suggests a temporary or permanent removal of this functionality.

If this change is temporary, consider adding a TODO or FIXME to revisit this. If permanent, ensure to clean up any references or dead code associated with this method.

let updateSourceField = await this.updateSourceDetailsTableFields(fieldsData.sourceDetails.table, sourceFieldName['name'], sourceFieldName['value'], sourceFieldName['controllingfieldfk']);
}
}
delete fieldsData.fieldParams;
Copy link

Choose a reason for hiding this comment

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

Performance consideration: Avoid using the delete operator.

The use of the delete operator on fieldsData.fieldParams can lead to performance issues due to deoptimization in JavaScript engines.

Consider setting the property to undefined instead of deleting it to maintain performance.

- delete fieldsData.fieldParams;
+ fieldsData.fieldParams = undefined;

Also applies to: 291-291

Tools
Biome

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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

Comment on lines +249 to +307
async updateFields(fieldId: any, request: any, fieldsUpdateDto: FieldsUpdateDto, response: Response) {
const apiId = APIID.FIELDS_CREATE;
try {
const fieldsData: any = {}; // Define an empty object to store field data
let storeWithoutControllingField = [];
let error = '';

Object.keys(fieldsUpdateDto).forEach((e) => {
if (fieldsUpdateDto[e] && fieldsUpdateDto[e] !== "") {
if (e === "render") {
fieldsData[e] = fieldsUpdateDto[e];
} else if (Array.isArray(fieldsUpdateDto[e])) {
fieldsData[e] = JSON.stringify(fieldsUpdateDto[e]);
} else {
fieldsData[e] = fieldsUpdateDto[e];
}
}
});

const getSourceDetails = await this.fieldsRepository.findOne({
where: { fieldId: fieldId }
});

console.log(getSourceDetails.dependsOn);


fieldsData['type'] = fieldsData.type || getSourceDetails.type;

if (getSourceDetails.fieldParams && getSourceDetails.sourceDetails && getSourceDetails.sourceDetails.source == 'table') {
for (let sourceFieldName of fieldsData.fieldParams.options) {
if (getSourceDetails.dependsOn && (!sourceFieldName['controllingfieldfk'] || sourceFieldName['controllingfieldfk'] === '')) {
storeWithoutControllingField.push(sourceFieldName['name'])
}
let query = `SELECT COUNT(*) FROM public.${getSourceDetails.sourceDetails.table} WHERE value = '${sourceFieldName['value']}'`;
const checkSourceData = await this.fieldsValuesRepository.query(query);

if (checkSourceData[0].count == 0) {
let createSourceField = await this.createSourceDetailsTableFields(getSourceDetails.sourceDetails.table, sourceFieldName['name'], sourceFieldName['value'], sourceFieldName['controllingfieldfk'], getSourceDetails.dependsOn);
} else {
let updateSourceField = await this.updateSourceDetailsTableFields(getSourceDetails.sourceDetails.table, sourceFieldName['name'], sourceFieldName['value'], sourceFieldName['controllingfieldfk']);
}
}
delete fieldsData.fieldParams;
}

if (storeWithoutControllingField.length > 0) {
let wrongControllingField = storeWithoutControllingField.join(',')
error = `Wrong Data: ${wrongControllingField} This field is dependent on another field and cannot be created without specifying the controllingfieldfk.`
}

let result = await this.fieldsRepository.update(fieldId, fieldsData);
return await APIResponse.success(response, apiId, result,
HttpStatus.CREATED, 'Fields updated successfully.')


} catch (e) {
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.

Updated updateFields method with new DTO.

The method now uses FieldsUpdateDto for updating field details. The logic checks for existing source details and updates or creates new entries accordingly.

The method's error handling and dynamic data handling capabilities are significantly improved.

However, consider adding more comments to clarify the logic, especially around the conditions in the loops.

+ // Check if source data exists and create or update accordingly
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 updateFields(fieldId: any, request: any, fieldsUpdateDto: FieldsUpdateDto, response: Response) {
const apiId = APIID.FIELDS_CREATE;
try {
const fieldsData: any = {}; // Define an empty object to store field data
let storeWithoutControllingField = [];
let error = '';
Object.keys(fieldsUpdateDto).forEach((e) => {
if (fieldsUpdateDto[e] && fieldsUpdateDto[e] !== "") {
if (e === "render") {
fieldsData[e] = fieldsUpdateDto[e];
} else if (Array.isArray(fieldsUpdateDto[e])) {
fieldsData[e] = JSON.stringify(fieldsUpdateDto[e]);
} else {
fieldsData[e] = fieldsUpdateDto[e];
}
}
});
const getSourceDetails = await this.fieldsRepository.findOne({
where: { fieldId: fieldId }
});
console.log(getSourceDetails.dependsOn);
fieldsData['type'] = fieldsData.type || getSourceDetails.type;
if (getSourceDetails.fieldParams && getSourceDetails.sourceDetails && getSourceDetails.sourceDetails.source == 'table') {
for (let sourceFieldName of fieldsData.fieldParams.options) {
if (getSourceDetails.dependsOn && (!sourceFieldName['controllingfieldfk'] || sourceFieldName['controllingfieldfk'] === '')) {
storeWithoutControllingField.push(sourceFieldName['name'])
}
let query = `SELECT COUNT(*) FROM public.${getSourceDetails.sourceDetails.table} WHERE value = '${sourceFieldName['value']}'`;
const checkSourceData = await this.fieldsValuesRepository.query(query);
if (checkSourceData[0].count == 0) {
let createSourceField = await this.createSourceDetailsTableFields(getSourceDetails.sourceDetails.table, sourceFieldName['name'], sourceFieldName['value'], sourceFieldName['controllingfieldfk'], getSourceDetails.dependsOn);
} else {
let updateSourceField = await this.updateSourceDetailsTableFields(getSourceDetails.sourceDetails.table, sourceFieldName['name'], sourceFieldName['value'], sourceFieldName['controllingfieldfk']);
}
}
delete fieldsData.fieldParams;
}
if (storeWithoutControllingField.length > 0) {
let wrongControllingField = storeWithoutControllingField.join(',')
error = `Wrong Data: ${wrongControllingField} This field is dependent on another field and cannot be created without specifying the controllingfieldfk.`
}
let result = await this.fieldsRepository.update(fieldId, fieldsData);
return await APIResponse.success(response, apiId, result,
HttpStatus.CREATED, 'Fields updated successfully.')
} catch (e) {
const errorMessage = e?.message || 'Something went wrong';
return APIResponse.error(response, apiId, "Internal Server Error", `Error : ${errorMessage}`, HttpStatus.INTERNAL_SERVER_ERROR)
}
async updateFields(fieldId: any, request: any, fieldsUpdateDto: FieldsUpdateDto, response: Response) {
const apiId = APIID.FIELDS_CREATE;
try {
const fieldsData: any = {}; // Define an empty object to store field data
let storeWithoutControllingField = [];
let error = '';
Object.keys(fieldsUpdateDto).forEach((e) => {
if (fieldsUpdateDto[e] && fieldsUpdateDto[e] !== "") {
if (e === "render") {
fieldsData[e] = fieldsUpdateDto[e];
} else if (Array.isArray(fieldsUpdateDto[e])) {
fieldsData[e] = JSON.stringify(fieldsUpdateDto[e]);
} else {
fieldsData[e] = fieldsUpdateDto[e];
}
}
});
const getSourceDetails = await this.fieldsRepository.findOne({
where: { fieldId: fieldId }
});
console.log(getSourceDetails.dependsOn);
fieldsData['type'] = fieldsData.type || getSourceDetails.type;
if (getSourceDetails.fieldParams && getSourceDetails.sourceDetails && getSourceDetails.sourceDetails.source == 'table') {
for (let sourceFieldName of fieldsData.fieldParams.options) {
if (getSourceDetails.dependsOn && (!sourceFieldName['controllingfieldfk'] || sourceFieldName['controllingfieldfk'] === '')) {
storeWithoutControllingField.push(sourceFieldName['name'])
}
let query = `SELECT COUNT(*) FROM public.${getSourceDetails.sourceDetails.table} WHERE value = '${sourceFieldName['value']}'`;
const checkSourceData = await this.fieldsValuesRepository.query(query);
if (checkSourceData[0].count == 0) {
let createSourceField = await this.createSourceDetailsTableFields(getSourceDetails.sourceDetails.table, sourceFieldName['name'], sourceFieldName['value'], sourceFieldName['controllingfieldfk'], getSourceDetails.dependsOn);
} else {
let updateSourceField = await this.updateSourceDetailsTableFields(getSourceDetails.sourceDetails.table, sourceFieldName['name'], sourceFieldName['value'], sourceFieldName['controllingfieldfk']);
}
}
// Check if source data exists and create or update accordingly
delete fieldsData.fieldParams;
}
if (storeWithoutControllingField.length > 0) {
let wrongControllingField = storeWithoutControllingField.join(',')
error = `Wrong Data: ${wrongControllingField} This field is dependent on another field and cannot be created without specifying the controllingfieldfk.`
}
let result = await this.fieldsRepository.update(fieldId, fieldsData);
return await APIResponse.success(response, apiId, result,
HttpStatus.CREATED, 'Fields updated successfully.')
} catch (e) {
const errorMessage = e?.message || 'Something went wrong';
return APIResponse.error(response, apiId, "Internal Server Error", `Error : ${errorMessage}`, HttpStatus.INTERNAL_SERVER_ERROR)
}
Tools
Biome

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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

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.

1 participant