nocobase/packages/database/src/magic-attribute-model.ts

60 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-01-07 12:26:23 +00:00
import { merge } from '@nocobase/utils';
import _ from 'lodash';
2022-01-07 14:06:31 +00:00
import Database from './database';
import { Model } from './model';
2022-01-07 12:26:23 +00:00
export class MagicAttributeModel extends Model {
2022-01-07 14:06:31 +00:00
get magicAttribute() {
const db: Database = (<any>this.constructor).database;
2022-01-07 14:06:31 +00:00
const collection = db.getCollection(this.constructor.name);
return collection.options.magicAttribute || 'options';
}
2022-01-07 12:26:23 +00: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 14:06:31 +00:00
const opts = super.get(this.magicAttribute) || {};
return super.set(`${this.magicAttribute}.${key}`, merge(opts?.[key], value), options);
2022-01-07 12:26:23 +00:00
}
2022-01-07 14:06:31 +00:00
return super.set(`${this.magicAttribute}.${key}`, value, options);
2022-01-07 12:26:23 +00: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-02-23 14:27:08 +00:00
const options = super.get(this.magicAttribute, value);
2022-01-07 12:26:23 +00:00
return _.get(options, key);
}
const data = super.get(key, value);
return {
2022-01-07 14:06:31 +00:00
..._.omit(data, this.magicAttribute),
...data[this.magicAttribute],
2022-01-07 12:26:23 +00:00
};
}
async update(values?: any, options?: any) {
// @ts-ignore
this._changed = new Set();
return super.update(values, options);
}
2022-01-07 14:06:31 +00:00
}