nocobase/packages/database/src/magic-attribute-model.ts
ChengLei Shao f67658129f
Feat/plugin UI schema v0.6 (#143)
* v0.6

* plugin-ui-schema: insert && getJsonSchema

* plugin-ui-schema: insert schema with sort

* plugin-ui-schema: node with x-index

* insert adjacent method

* chore: insert

* typo

* insert with x-uid

* fix: getSchema by subtree

* add ui-schema actions

* fix: mysql compatibility

* remove ui-schema when remove node tree

* ui schema patch

* ui_schemas.create

* test cases

* test cases

* fix(database): reset changed before update

* feat: insert ui schema node after created

* feat:  patch ui schema node after updated

* fix: sqlite error

* uid

* cleanup

* test cases

* feat: ui_schema items type support

* fix: insert items node

* fix: get inner type

* change items struct

* add insert return value

* add insert return value

Co-authored-by: chenos <chenlinxh@gmail.com>
2022-01-19 10:09:30 +08:00

60 lines
1.8 KiB
TypeScript

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 = (<any>this.constructor).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('.');
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)) {
const opts = super.get(this.magicAttribute) || {};
return super.set(`${this.magicAttribute}.${key}`, merge(opts?.[key], value), options);
}
return super.set(`${this.magicAttribute}.${key}`, value, options);
} 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);
}
const options = super.get(this.magicAttribute);
return _.get(options, key);
}
const data = super.get(key, value);
return {
..._.omit(data, this.magicAttribute),
...data[this.magicAttribute],
};
}
async update(values?: any, options?: any) {
// @ts-ignore
this._changed = new Set();
return super.update(values, options);
}
}