Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/pinia-orm/src/model/Model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -826,11 +826,18 @@ export class Model {

if (cast && operation === 'get') { value = cast.get(value) }

// Apply the cast before the field is filled so the type check
// validates the casted value instead of the raw input.
if (cast && operation === 'set' && value !== undefined) {
value = options.action === 'update' ? cast.get(value) : cast.set(value)
}

let keyValue = this.$fillField(key, attr, value)

if (mutator && typeof mutator !== 'function' && operation === 'set' && mutator.set) { keyValue = mutator.set(keyValue) }

if (cast && operation === 'set') {
// Values filled by the attribute default still need to pass the cast.
if (cast && operation === 'set' && value === undefined) {
keyValue = options.action === 'update' ? cast.get(keyValue) : cast.set(keyValue)
}

Expand Down
30 changes: 30 additions & 0 deletions packages/pinia-orm/tests/unit/model/Model_Casts_Number.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,34 @@ describe('unit/model/Model_Casts_Number', () => {

expect(userRepo.find(1)?.count).toBe(444)
})

it('should not warn about a wrong type when the cast converts the value on save', () => {
const warningSpy = vi.spyOn(console, 'warn')
warningSpy.mockClear()

class User extends Model {
static entity = 'users'

@Attr(0) id!: number

@Cast(() => NumberCast)
@Num(null)
count!: number | null
}

const userRepo = useRepo(User)
userRepo.save({
id: 1,
count: '10191',
})

assertState({
users: {
1: { id: 1, count: 10191 },
},
})

expect(userRepo.find(1)?.count).toBe(10191)
expect(warningSpy).not.toHaveBeenCalled()
})
})
Loading