fix(plugin-cm): fix field disappear after failed to update (#773)

This commit is contained in:
Junyi 2022-08-24 11:51:14 +08:00 committed by GitHub
parent 13dd078079
commit d1b52c7d96
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 6 deletions

View File

@ -51,6 +51,12 @@ describe('field indexes', () => {
}
});
expect(response3.status).toBe(400);
const response4 = await agent.resource(tableName).create({
values: { title: 't1' }
});
expect(response4.status).toBe(200);
expect(response4.body.data.title).toBe('t1');
});
it('field value cannot be duplicated with unique index', async () => {

View File

@ -6,7 +6,9 @@ interface LoadOptions extends Transactionable {
skipExist?: boolean;
}
interface MigrateOptions extends SyncOptions, Transactionable {}
interface MigrateOptions extends SyncOptions, Transactionable {
isNew?: boolean;
}
async function migrate(field: Field, options: MigrateOptions): Promise<void> {
const { unique } = field.options;
@ -75,19 +77,22 @@ export class FieldModel extends MagicAttributeModel {
return collection.setField(name, options);
}
async migrate(options: MigrateOptions = {}) {
async migrate({ isNew, ...options }: MigrateOptions = {}) {
const field = await this.load({
transaction: options.transaction,
});
if (!field) {
return;
}
// const migrator = Dialects[field.database.options.dialect] ?? migrate;
try {
await migrate(field, options);
} catch (error) {
// field sync failed, delete from memory
field.remove();
if (isNew) {
// update field should not remove field from memory
field.remove();
}
throw error;
}
}

View File

@ -65,13 +65,19 @@ export class CollectionManagerPlugin extends Plugin {
this.app.db.on('collections.afterCreateWithAssociations', async (model, { context, transaction }) => {
if (context) {
await model.migrate({ transaction });
await model.migrate({
isNew: true,
transaction
});
}
});
this.app.db.on('fields.afterCreate', async (model: FieldModel, { context, transaction }) => {
if (context) {
await model.migrate({ transaction });
await model.migrate({
isNew: true,
transaction
});
}
});