Skip to content

optimisticDelete

optimisticDelete<TEntity>(em, entityType, aggregate, entityName): Promise<void>

Defined in: packages/ddd-mikro-orm/src/concurrency/optimistic-delete.ts:55

Executes a single version-conditioned, autocommitted DELETE on an aggregate.

The delete counterpart of optimisticUpdate, with the same contract:

  • rejects an externally active transaction before touching the database (assertAutocommit);
  • deletes on { id, version: aggregate.getExpectedVersion() }, so a row modified since the aggregate was loaded is not removed;
  • one affected row is success;
  • zero rows runs one refreshed diagnostic read: an absent row is EntityNotFoundException, a present row is ConcurrencyConflictError;
  • any other count is an invariant violation, since the filter includes a primary key.

The caller passes em once and this helper uses exactly that instance for both the delete and the diagnostic read, so the two cannot observe different transactional state.

Caching, aggregate acknowledgment and event publication stay with @Cache, @AcknowledgePersisted and CommandBaseHandler. A delete repository resolves to null: there is no new persisted snapshot to acknowledge.

Rows without a version column are out of scope; delete them by primary key.

TEntity extends VersionedAggregate

EntityManager

Entity manager in autocommit mode.

EntityName<TEntity>

Entity class or registered name.

TEntity

Aggregate providing id and getExpectedVersion().

string

Friendly name for diagnostics, e.g. 'User'.

Promise<void>

Inside an active transaction, or on an unexpected row count.

No row matched and the entity is gone.

No row matched because the version diverged.

Delete command repository

@Cache<User, null>({ deleteKeys: (user) => [cacheKey(User.aggregateName, { id: user.id })] })
@MapPersistenceErrors<[User], User>({
entity: ([user]) => user,
otherwise: (error, user) => mapPersistenceError(error, `deleting User ${user.id}`),
})
async save(user: User): Promise<null> {
await optimisticDelete(this.store.em, User, user, 'User');
return null;
}