feat(database): add trim option for string field (#6565)

* feat(database): add trim option for string field

* refactor(database): change to setDataValue instead of hooks

* fix(database): fix test case of view collection
This commit is contained in:
Junyi 2025-04-01 13:25:08 +08:00 committed by GitHub
parent 69fac11204
commit 4c3255d455
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 33 additions and 1 deletions

View File

@ -62,6 +62,12 @@ export class InputFieldInterface extends CollectionFieldInterface {
hasDefaultValue = true; hasDefaultValue = true;
properties = { properties = {
...defaultProps, ...defaultProps,
trim: {
type: 'boolean',
'x-content': '{{t("Automatically remove heading and tailing spaces")}}',
'x-decorator': 'FormItem',
'x-component': 'Checkbox',
},
layout: { layout: {
type: 'void', type: 'void',
title: '{{t("Index")}}', title: '{{t("Index")}}',

View File

@ -258,6 +258,7 @@
"Parent collection fields": "父表字段", "Parent collection fields": "父表字段",
"Basic": "基本类型", "Basic": "基本类型",
"Single line text": "单行文本", "Single line text": "单行文本",
"Automatically remove heading and tailing spaces": "自动去除首尾空白字符",
"Long text": "多行文本", "Long text": "多行文本",
"Phone": "手机号码", "Phone": "手机号码",
"Email": "电子邮箱", "Email": "电子邮箱",

View File

@ -105,4 +105,18 @@ describe('string field', () => {
name2: 'n2111', name2: 'n2111',
}); });
}); });
it('trim', async () => {
const collection = db.collection({
name: 'tests',
fields: [{ type: 'string', name: 'name', trim: true }],
});
await db.sync();
const model = await collection.model.create({
name: ' n1\n ',
});
expect(model.toJSON()).toMatchObject({
name: 'n1',
});
});
}); });

View File

@ -8,7 +8,7 @@
*/ */
import { DataTypes } from 'sequelize'; import { DataTypes } from 'sequelize';
import { BaseColumnFieldOptions, Field } from './field'; import { BaseColumnFieldOptions, Field, FieldContext } from './field';
export class StringField extends Field { export class StringField extends Field {
get dataType() { get dataType() {
@ -18,9 +18,20 @@ export class StringField extends Field {
return DataTypes.STRING; return DataTypes.STRING;
} }
additionalSequelizeOptions() {
const { name, trim } = this.options;
return {
set(value) {
this.setDataValue(name, trim ? value?.trim() : value);
},
};
}
} }
export interface StringFieldOptions extends BaseColumnFieldOptions { export interface StringFieldOptions extends BaseColumnFieldOptions {
type: 'string'; type: 'string';
length?: number; length?: number;
trim?: boolean;
} }