fix(database): fix trim option for string and text field (#6797)

This commit is contained in:
Junyi 2025-04-28 21:17:05 +08:00 committed by GitHub
parent 3b1b4cfef5
commit 823d67ac13
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 70 additions and 2 deletions

View File

@ -119,4 +119,32 @@ describe('string field', () => {
name: 'n1',
});
});
it('trim when value is null should be null', async () => {
const collection = db.collection({
name: 'tests',
fields: [{ type: 'string', name: 'name', trim: true }],
});
await db.sync();
const model = await collection.model.create({
name: null,
});
expect(model.toJSON()).toMatchObject({
name: null,
});
});
it('when value is number should be convert to string', async () => {
const collection = db.collection({
name: 'tests',
fields: [{ type: 'string', name: 'name', trim: true }],
});
await db.sync();
const model = await collection.model.create({
name: 123,
});
expect(model.toJSON()).toMatchObject({
name: '123',
});
});
});

View File

@ -66,4 +66,32 @@ describe('text field', () => {
name: 'n1',
});
});
it('trim when value is null should be null', async () => {
const collection = db.collection({
name: 'tests',
fields: [{ type: 'string', name: 'name', trim: true }],
});
await db.sync();
const model = await collection.model.create({
name: null,
});
expect(model.toJSON()).toMatchObject({
name: null,
});
});
it('when value is number should be convert to string', async () => {
const collection = db.collection({
name: 'tests',
fields: [{ type: 'string', name: 'name', trim: true }],
});
await db.sync();
const model = await collection.model.create({
name: 123,
});
expect(model.toJSON()).toMatchObject({
name: '123',
});
});
});

View File

@ -24,7 +24,13 @@ export class StringField extends Field {
return {
set(value) {
this.setDataValue(name, trim ? value?.trim() : value);
if (value == null) {
return value;
}
if (typeof value !== 'string') {
value = value.toString();
}
this.setDataValue(name, trim ? value.trim() : value);
},
};
}

View File

@ -29,7 +29,13 @@ export class TextField extends Field {
return {
set(value) {
this.setDataValue(name, trim ? value?.trim() : value);
if (value == null) {
return value;
}
if (typeof value !== 'string') {
value = value.toString();
}
this.setDataValue(name, trim ? value.trim() : value);
},
};
}