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

63 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-01-07 20:26:23 +08:00
import { merge } from '@nocobase/utils';
import _ from 'lodash';
2022-01-07 22:06:31 +08:00
import Database from './database';
import { Model } from './model';
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 = (<any>this.constructor).database;
2022-01-07 22:06:31 +08:00
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 {
if (!key) {
return;
}
2022-01-07 20:26:23 +08:00
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 22:27:08 +08:00
const options = super.get(this.magicAttribute, value);
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
};
}
async update(values?: any, options?: any) {
// @ts-ignore
this._changed = new Set();
return super.update(values, options);
}
2022-01-07 22:06:31 +08:00
}