Skip to content

Add type inference to loadBeforeMutationEntities and loadAfterMutationEntities #282

@genu

Description

@genu

Is there a reliable way to infer the proper return type of loadAfterMutationEntities and loadBeforeMutationEntities?

/**
* Loads the entities that have been mutated.
*/
loadAfterMutationEntities(): Promise<Record<string, unknown>[] | undefined>;

/**
* Loads the entities that are about to be mutated. The db operation that loads the entities is executed
* within the same transaction context as the mutation.
*/
loadBeforeMutationEntities(): Promise<Record<string, unknown>[] | undefined>;

If the return data is typed, it becomes easier working with any follow up queries:

export const onAfterPostDelete = definePlugin<SchemaType>({
  id: "onAfterPostDelete",
  onEntityMutation: {
    async beforeEntityMutation({ model, action, loadBeforeMutationEntities, client, queryId }) {
      const deletedPost = await loadBeforeMutationEntities() // <--- typed as Record<string, unknown>[] | undefined but its really a Post[]

      if (action === "delete" && model === "Post") {
        // Do some logic
        const tags = await client.tag.findMany({
          where: {
            postId: deletedPost[0].id, // <-- This doesn't work unless we cast deletedPost to proper type like Post[]
          },
        })
      }
    },
  },
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions