feat: customizable magicAttribute

This commit is contained in:
chenos 2022-01-07 22:06:31 +08:00
parent 103a170917
commit 10d520c22a
3 changed files with 61 additions and 7 deletions

View File

@ -40,4 +40,44 @@ describe('magic-attribute-model', () => {
'x-decorator-props': { key1: 'val1' },
});
});
it('case 2', async () => {
const db = mockDatabase();
db.registerModels({ MagicAttributeModel });
const Test = db.collection({
name: 'tests',
model: 'MagicAttributeModel',
magicAttribute: 'schema',
fields: [
{ type: 'string', name: 'title' },
{ type: 'json', name: 'schema' },
],
});
await db.sync();
const test = await Test.model.create({
title: 'aa',
'x-component-props': { key1: 'val1', arr1: [1, 2, 3], arr2: [4, 5] },
});
test.set({
'x-component-props': { key2: 'val2', arr1: [3, 4] },
'x-decorator-props': { key1: 'val1' },
});
test.set('x-component-props', { arr2: [1, 2, 3] });
expect(test.toJSON()).toMatchObject({
title: 'aa',
'x-component-props': {
key1: 'val1',
key2: 'val2',
arr1: [3, 4],
arr2: [1, 2, 3],
},
'x-decorator-props': { key1: 'val1' },
});
});
});

View File

@ -19,7 +19,14 @@ export interface CollectionOptions extends Omit<ModelOptions, 'name'> {
fields?: FieldOptions[];
model?: string | ModelCtor<Model>;
repository?: string | RepositoryType;
/**
* @default true
*/
autoGenId?: boolean;
/**
* @default 'options'
*/
magicAttribute?: string;
[key: string]: any;
}

View File

@ -1,8 +1,15 @@
import { Model } from 'sequelize';
import { merge } from '@nocobase/utils';
import _ from 'lodash';
import Database from './database';
export class MagicAttributeModel extends Model {
get magicAttribute() {
const db: Database = (this.constructor as any).database;
const collection = db.getCollection(this.constructor.name);
return collection.options.magicAttribute || 'options';
}
set(key: any, value?: any, options?: any) {
if (typeof key === 'string') {
const [column] = key.split('.');
@ -13,10 +20,10 @@ export class MagicAttributeModel extends Model {
return super.set(key, value, options);
}
if (_.isPlainObject(value)) {
const opts = super.get(`options`) || {};
return super.set(`options.${key}`, merge(opts?.[key], value), options);
const opts = super.get(this.magicAttribute) || {};
return super.set(`${this.magicAttribute}.${key}`, merge(opts?.[key], value), options);
}
return super.set(`options.${key}`, value, options);
return super.set(`${this.magicAttribute}.${key}`, value, options);
} else {
Object.keys(key).forEach((k) => {
this.set(k, key[k], options);
@ -34,13 +41,13 @@ export class MagicAttributeModel extends Model {
if ((this.constructor as any).rawAttributes[column]) {
return super.get(key, value);
}
const options = super.get(`options`);
const options = super.get(this.magicAttribute);
return _.get(options, key);
}
const data = super.get(key, value);
return {
..._.omit(data, 'options'),
...data.options,
..._.omit(data, this.magicAttribute),
...data[this.magicAttribute],
};
}
}
}