MCPcopy Create free account
hub / github.com/mikro-orm/mikro-orm / refresh

Method refresh

packages/core/src/EntityManager.ts:970–1020  ·  view source on GitHub ↗

* Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been * persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer * in database, the method returns `null`.

(
    entity: Entity,
    options: FindOneOptions<Entity, Hint, Fields, Excludes> = {},
  )

Source from the content-addressed store, hash-verified

968 * in database, the method returns `null`.
969 */
970 async refresh<
971 Entity extends object,
972 Naked extends FromEntityType<Entity> = FromEntityType<Entity>,
973 Hint extends string = never,
974 Fields extends string = never,
975 Excludes extends string = never,
976 >(
977 entity: Entity,
978 options: FindOneOptions<Entity, Hint, Fields, Excludes> = {},
979 ): Promise<MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true> | null> {
980 const fork = this.fork({ keepTransactionContext: true });
981 const wrapped = helper(entity);
982 const reloaded = await fork.findOne(wrapped.__meta.class, entity, {
983 schema: wrapped.__schema,
984 ...options,
985 flushMode: FlushMode.COMMIT,
986 });
987
988 const em = this.getContext();
989
990 if (!reloaded) {
991 em.#unitOfWork.unsetIdentity(entity);
992 return null;
993 }
994
995 let found = false;
996
997 for (const e of fork.#unitOfWork.getIdentityMap()) {
998 const ref = em.getReference(e.constructor, helper(e).getPrimaryKey());
999 const data = helper(e).serialize({ ignoreSerializers: true, includeHidden: true, convertCustomTypes: false });
1000 em.config
1001 .getHydrator(this.metadata)
1002 .hydrate(ref, helper(ref).__meta, data, em.#entityFactory, 'full', false, false);
1003 Utils.merge(helper(ref).__originalEntityData, this.#comparator.prepareEntity(e as Entity));
1004 found ||= ref === entity;
1005 }
1006
1007 if (!found) {
1008 const data = helper(reloaded).serialize({
1009 ignoreSerializers: true,
1010 includeHidden: true,
1011 convertCustomTypes: false,
1012 }) as object;
1013 em.config
1014 .getHydrator(this.metadata)
1015 .hydrate(entity, wrapped.__meta, data, em.#entityFactory, 'full', false, false);
1016 Utils.merge(wrapped.__originalEntityData, this.#comparator.prepareEntity(reloaded as Entity));
1017 }
1018
1019 return entity as any;
1020 }
1021
1022 /**
1023 * Finds first entity matching your `where` query.

Callers 1

refreshOrFailMethod · 0.95

Calls 13

forkMethod · 0.95
getContextMethod · 0.95
helperFunction · 0.85
unsetIdentityMethod · 0.80
getIdentityMapMethod · 0.80
prepareEntityMethod · 0.80
findOneMethod · 0.65
getPrimaryKeyMethod · 0.65
serializeMethod · 0.65
hydrateMethod · 0.65
getReferenceMethod · 0.45
getHydratorMethod · 0.45

Tested by

no test coverage detected