Skip to content

Create own context for mutation response resolvers #1308

Closed
@mxstbr

Description

@mxstbr

Imagine a mutation top edit a users username, which has a signature something like this:

type Mutation {
  changeUsername(username: String!): User
}

mutation changeUsername($username: String!) {
  changeUsername(username: $username {
    username
  }
}

In said mutation resolver, I now have to load the user for whatever reason. (in my real use case for checking permissions) I'm using DataLoader to do so to avoid repeated database calls:

const RootMutation = {
  changeUsername: (root, args, context) => {
    const user = context.loaders.user.load(args.input.id);
    // ...actual username changing code...
  }
}

In my query resolvers I also use the same loader to resolve a user object:

const RootQuery = {
  user: (root, args, context) => {
    return context.loaders.user.load(root.id || args.id)
  }
}

The issue I'm running into is that the query resolver for the single user returns the cached data from the dataloader without the new changes because the context is shared between the mutation resolver and the returned query resolvers:

this.props.changeUsername('new-username').then(result => {
  console.log(result) // { username: 'old-username' }
})

Now, in this specific case I can work around this by manually clearing the DataLoader cache with context.loaders.user.clear(id). I'm wondering though, maybe it'd make sense to create the context anew for the resolvers of a mutations return value vs. for the mutation resolver itself?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions