feat: fallback sort field init to createdAt field (#1507)

* feat: fallback sort field init to createdAt field when primary key not exists

* chore: set belongsToMany through autoCreated table to sortable false
This commit is contained in:
ChengLei Shao 2023-02-27 13:59:17 +08:00 committed by GitHub
parent 303139bc9f
commit ecf618783e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 61 additions and 2 deletions

View File

@ -17,6 +17,29 @@ describe('string field', () => {
await db.close();
});
it('should init sorted value by createdAt when primaryKey not exists', async () => {
const Test = db.collection({
autoGenId: false,
name: 'tests',
});
await db.sync();
await Test.repository.create({
values: [{}, {}, {}],
});
// add sort field
Test.setField('sort', { type: 'sort' });
let err;
try {
await db.sync();
} catch (e) {
err = e;
}
expect(err).toBeFalsy();
});
it('sort', async () => {
const Test = db.collection({
name: 'tests',

View File

@ -53,9 +53,21 @@ export class SortField extends Field {
transaction,
});
const orderKey = (() => {
const model = this.collection.model;
if (model.primaryKeyAttribute) {
return model.primaryKeyAttribute;
}
if (model.rawAttributes['createdAt']) {
return 'createdAt';
}
throw new Error(`can not find order key for collection ${this.collection.name}`);
})();
if (emptyCount === totalCount && emptyCount > 0) {
const records = await this.collection.repository.find({
order: [this.collection.model.primaryKeyAttribute],
order: [orderKey],
transaction,
});

View File

@ -17,11 +17,14 @@ describe('belongsToMany', () => {
values: {
name: 'posts',
},
context: {},
});
await Collection.repository.create({
values: {
name: 'tags',
},
context: {},
});
});
@ -29,5 +32,24 @@ describe('belongsToMany', () => {
await app.destroy();
});
it('should create belongsToMany field', async () => {});
it('should create belongsToMany field', async () => {
await Field.repository.create({
values: {
name: 'tags',
type: 'belongsToMany',
collectionName: 'posts',
interface: 'm2m',
through: 'post_tags',
},
context: {},
});
const throughCollection = await Collection.repository.findOne({
filter: {
name: 'post_tags',
},
});
expect(throughCollection.get('sortable')).toEqual(false);
});
});

View File

@ -150,6 +150,7 @@ export function afterCreateForForeignKeyField(db: Database) {
hidden: true,
autoCreate: true,
isThrough: true,
sortable: false,
},
transaction,
});

View File

@ -80,6 +80,7 @@ export class PresetNocoBase extends Plugin {
// }
// }
});
this.app.on('beforeUpgrade', async (options) => {
const result = await this.app.version.satisfies('<0.8.0-alpha.1');
if (result) {