Skip to content

Commit

Permalink
feat: Handled edge cases with find & replace in number column
Browse files Browse the repository at this point in the history
  • Loading branch information
chavda-bhavik committed Sep 12, 2024
1 parent 6152a7e commit e6de014
Showing 1 changed file with 33 additions and 17 deletions.
50 changes: 33 additions & 17 deletions apps/api/src/app/review/usecases/replace/replace.usecase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,22 +64,32 @@ export class Replace {
},
};
replaceOperation = {
$cond: {
if: { $eq: [formattedReplace, ''] },
then: null,
else: {
$cond: {
if: { $eq: [{ $type: '$' + path }, 'number'] },
then: {
$toDouble: {
$replaceAll: {
input: { $toString: '$' + path },
find: find,
replacement: formattedReplace,
},
},
$let: {
vars: {
stringValue: { $toString: '$' + path },
replacedValue: {
$replaceAll: {
input: { $toString: '$' + path },
find: find,
replacement: { $toString: formattedReplace },
},
else: formattedReplace,
},
},
in: {
$switch: {
branches: [
// Case 1: No change
{ case: { $eq: ['$$stringValue', '$$replacedValue'] }, then: `$${path}` },
// Case 2: Result is empty
{ case: { $eq: ['$$replacedValue', ''] }, then: null },
// Case 3: Result is a valid number
{
case: { $regexMatch: { input: '$$replacedValue', regex: /^-?\d*\.?\d+$/ } },
then: { $toDouble: '$$replacedValue' },
},
],
// Default: Keep as string if not a valid number
default: '$$replacedValue',
},
},
},
Expand Down Expand Up @@ -111,13 +121,19 @@ export class Replace {
},
});

// Update the 'updated' flag only if _oldRecord exists and the value has changed
updateStages.push({
$set: {
[`updated.${fieldName}`]: {
$cond: {
if: { $ne: [`$record.${fieldName}`, `$_oldRecord.${fieldName}`] },
if: {
$and: [
{ $ifNull: ['$_oldRecord', false] },
{ $ne: [`$record.${fieldName}`, `$_oldRecord.${fieldName}`] },
],
},
then: true,
else: '$$REMOVE',
else: { $ifNull: [`$updated.${fieldName}`, '$$REMOVE'] },
},
},
},
Expand Down

0 comments on commit e6de014

Please sign in to comment.