2022-01-07 20:26:23 +08:00
|
|
|
import { Model } from 'sequelize';
|
|
|
|
import { merge } from '@nocobase/utils';
|
|
|
|
import _ from 'lodash';
|
2022-01-07 22:06:31 +08:00
|
|
|
import Database from './database';
|
2022-01-07 20:26:23 +08:00
|
|
|
|
|
|
|
export class MagicAttributeModel extends Model {
|
2022-01-07 22:06:31 +08:00
|
|
|
get magicAttribute() {
|
|
|
|
const db: Database = (this.constructor as any).database;
|
|
|
|
const collection = db.getCollection(this.constructor.name);
|
|
|
|
return collection.options.magicAttribute || 'options';
|
|
|
|
}
|
|
|
|
|
2022-01-07 20:26:23 +08:00
|
|
|
set(key: any, value?: any, options?: any) {
|
|
|
|
if (typeof key === 'string') {
|
|
|
|
const [column] = key.split('.');
|
|
|
|
if ((this.constructor as any).hasAlias(column)) {
|
|
|
|
return super.set(key, value, options);
|
|
|
|
}
|
|
|
|
if ((this.constructor as any).rawAttributes[column]) {
|
|
|
|
return super.set(key, value, options);
|
|
|
|
}
|
|
|
|
if (_.isPlainObject(value)) {
|
2022-01-07 22:06:31 +08:00
|
|
|
const opts = super.get(this.magicAttribute) || {};
|
|
|
|
return super.set(`${this.magicAttribute}.${key}`, merge(opts?.[key], value), options);
|
2022-01-07 20:26:23 +08:00
|
|
|
}
|
2022-01-07 22:06:31 +08:00
|
|
|
return super.set(`${this.magicAttribute}.${key}`, value, options);
|
2022-01-07 20:26:23 +08:00
|
|
|
} else {
|
|
|
|
Object.keys(key).forEach((k) => {
|
|
|
|
this.set(k, key[k], options);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return super.set(key, value, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
get(key?: any, value?: any): any {
|
|
|
|
if (typeof key === 'string') {
|
|
|
|
const [column] = key.split('.');
|
|
|
|
if ((this.constructor as any).hasAlias(column)) {
|
|
|
|
return super.get(key, value);
|
|
|
|
}
|
|
|
|
if ((this.constructor as any).rawAttributes[column]) {
|
|
|
|
return super.get(key, value);
|
|
|
|
}
|
2022-01-07 22:06:31 +08:00
|
|
|
const options = super.get(this.magicAttribute);
|
2022-01-07 20:26:23 +08:00
|
|
|
return _.get(options, key);
|
|
|
|
}
|
|
|
|
const data = super.get(key, value);
|
|
|
|
return {
|
2022-01-07 22:06:31 +08:00
|
|
|
..._.omit(data, this.magicAttribute),
|
|
|
|
...data[this.magicAttribute],
|
2022-01-07 20:26:23 +08:00
|
|
|
};
|
|
|
|
}
|
2022-01-07 22:06:31 +08:00
|
|
|
}
|