Skip to content

Commit

Permalink
fix: ensure nested autoValue is called for modifiers that don't set t…
Browse files Browse the repository at this point in the history
…he parent

fixes #277
  • Loading branch information
aldeed committed Feb 25, 2024
1 parent ded2a35 commit 2acf9b1
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/clean/getPositionsForAutoValue.ts
Expand Up @@ -5,6 +5,7 @@ import { getLastPartOfKey, getParentOfKey } from '../utility/index.js'
interface GetPositionsForAutoValueProps {
fieldName: string
isModifier?: boolean
isUpsert?: boolean
mongoObject: MongoObject
}

Expand Down Expand Up @@ -42,6 +43,7 @@ interface PositionInfo {
export default function getPositionsForAutoValue ({
fieldName,
isModifier,
isUpsert,
mongoObject
}: GetPositionsForAutoValueProps): PositionInfo[] {
// Positions for this field
Expand Down Expand Up @@ -130,5 +132,17 @@ export default function getPositionsForAutoValue ({
})
}

// If we made it this far, we still want to call the autoValue
// function once for the field, so we'll add a would-be position for it.
if (positions.length === 0 && isModifier === true && isUpsert !== true) {
positions.push({
key: fieldName,
// @ts-expect-error incorrect type in mongo-object package
value: undefined,
operator: '$set',
position: `$set[${fieldName}]`
})
}

return positions
}
1 change: 1 addition & 0 deletions src/clean/setAutoValues.ts
Expand Up @@ -69,6 +69,7 @@ function setAutoValues (
const positions = getPositionsForAutoValue({
fieldName,
isModifier,
isUpsert,
mongoObject
})

Expand Down
36 changes: 36 additions & 0 deletions test/SimpleSchema_autoValueFunctions.tests.ts
Expand Up @@ -153,4 +153,40 @@ describe('SimpleSchema - autoValueFunctions', function () {
expect(autoValueFunctions[1].fieldName).toBe('a.b.$.z')
expect(autoValueFunctions[1].closestSubschemaFieldName).toBe('a.b.$')
})

it('modifier with autovalue in subschema', function () {
const datesSchema = new SimpleSchema({
updatedAt: {
type: Date,
label: 'Updated At',
optional: true,
autoValue: function () {
return new Date()
}
}
})

const schema = new SimpleSchema({
otherStuff: {
type: String,
optional: true
},
dates: {
type: datesSchema,
label: 'Dates',
optional: true,
defaultValue: {}
}
})

const modifier = {
$set: { otherStuff: 'someOtherString' }
}

const cleanedModifier = schema.clean(modifier, {
isModifier: true
}) as any
expect(cleanedModifier.$set['dates.updatedAt']).not.toBeUndefined()
expect(cleanedModifier.$set['dates.updatedAt']).toBeInstanceOf(Date)
})
})

0 comments on commit 2acf9b1

Please sign in to comment.