tachybase_todo/packages/database-next/src/fields/sort-field.ts

26 lines
661 B
TypeScript
Raw Normal View History

2021-09-23 00:16:04 +08:00
import { isNumber } from 'lodash';
import { DataTypes } from 'sequelize';
2021-09-27 15:28:32 +08:00
import { Field } from './field';
2021-09-23 00:16:04 +08:00
2021-09-27 15:28:32 +08:00
export class SortField extends Field {
2021-09-23 00:16:04 +08:00
get dataType() {
return DataTypes.INTEGER;
}
init() {
const { name, scopeKey } = this.options;
const { model } = this.context.collection;
model.beforeCreate(async (instance, options) => {
if (isNumber(instance.get(name))) {
return;
}
const where = {};
if (scopeKey) {
where[scopeKey] = instance.get(scopeKey);
}
const max = await model.max<number, any>(name, { ...options, where });
instance.set(name, (max || 0) + 1);
});
}
}