#2380·mikro-orm

Read-only EntityManager forking

Author: parisholleyCreated Nov 8, 2021Updated Nov 15, 2022
Labelsenhancement

In coming up with a solution to flush less (see https://github.com/mikro-orm/mikro-orm/issues/2379), i realized one aspect that may help is the ability to access a read-only version of the entity manager that would effectively never flush or write to the database (and perhaps see some performance wins by reducing the about of operations ran during various API calls) and only support select queries (and perhaps throw an error if the user attempts to invoke persist or some other modifying function, though wouldn't protect from raw queries).

example, if a GraphQL request comes in for mutating, it will auto-flush, but if it is a standard query, it will return a version which prevents modifications and disable auto flushing:

typescript
  const override = () => {
    throw new Error('Cannot perform write operations in a read-only manager.');
  };

  em.persist = override;
  em.transactional = override;
  em.flush = override;
  em.remove = override;
  em.nativeDelete = override;
  em.nativeInsert = override;
  em.nativeUpdate = override;

  return em;