Search code examples
node.jstypescriptgraphqltypegraphqlmikro-orm

cached data by mikro-orm using type-graphql


i'm trying mikro-orm, so i made a simple CRUD resolver, but i saw from the graphql debug console that after a delete like:

mutation{
  deleteItem(id:9)
}

Having the following code

 @Mutation(() => Boolean)
 async deleteItem(@Arg('id') id: number, @Ctx() { em }: MyContext): Promise<boolean> {
   try {
     await em.nativeDelete(Item, { id });
     return true;
   } catch (error) {
     console.log(error);
     return false;
   }
 }

the response as expected is ok.

But if i try to edit the deleted item, the edited item is returned...even with mikro-orm cache disabled cache: { enabled: false }, Where is the error? Do i need to force some flush?

this is the editItem resolver:


  @Mutation(() => Item, { nullable: true })
  async editItem(
    @Arg('id') id: number,
    @Arg('data', () => String, { nullable: true }) data: string,
    @Ctx() { em }: MyContext
  ): Promise<Item | null> {
    const item = await em.findOne(Item, { id });
    if (!item) {
      return null;
    }
    console.log(item);
    if (typeof data !== 'undefined') {
      post.data = data;
      await em.persistAndFlush(item);
    }
    return item;
  }

Thanks


Solution

  • even with mikro-orm cache disabled cache: { enabled: false }

    That is metadata cache, and it is disabled by default unless you use ts-morph.

    em.nativeDelete() won't remove anything from the identity map, so if you have that entity loaded in given context, querying via its PK will always return the entity from identity map without querying the db.

    In general this should be fine, as the delete request have its own context - are you handling request context properly? Either via em.fork() or via RequestContext helper. It is required.

    https://mikro-orm.io/docs/identity-map

    If this happens in a single context on purpose, you could use em.removeAndFlush(em.getReference()) which will remove that item from identity map.