【问题标题】:Update graphql context in a mutation for the output object of the same mutation更新同一突变的输出对象的突变中的graphql上下文
【发布时间】:2023-03-12 23:01:01
【问题描述】:

我想为应用程序使用单个突变将用户信息发送到服务器,然后在输出中获取顶级查询。 (我知道这不是一个好的约定,但我想这样做以测试我是否可以提高性能)。

因此,只有一个突变会获取用户信息并返回提要。此突变将在每个查询中获取的有关用户的信息更新为请求的上下文。上下文用于生成个性化提要。但是,当我调用此突变时,返回的输出是使用旧上下文计算的。我需要做的就是更新这个相同突变的上下文。

我写下代码的简化版本来显示发生了什么:



const UserType = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
    someData: {
      type: GraphQLList(Post),
      resolve: (user, args, context) => getFeed(context) // context in here is the old context.
    },
  })
})

const someMutation = mutationWithClientMutationId({
  name: 'someMutation',
  inputFields: {
    location: { type: GraphQLString },
  },
  outputFields: {
    user: {
      type: UserType,
      resolve: (source, args, context) => getUser(context.location),
    },
  },
  mutateAndGetPayload: async (data, context) => {

    updateUserInfo(data)
    // I have tried updating context like this but it's not working.
    context = { location: data.location }

    return {
        // I even tried putting user here like this:
        // user: getUser(data.location)
        // However, the resulting query fails when running getFeed(context)
        // the context is still the old context
    }
  },
})

【问题讨论】:

    标签: javascript graphql javascript-objects graphql-js


    【解决方案1】:

    这就是 JavaScript 的工作原理。您可以重新分配函数参数的值,但这不会更改函数传递的值。

    function makeTrue (value) {
      value = true
      console.log(value) // true
    }
    
    var myVariable = false
    makeTrue(myVariable)
    console.log(myVariable) // false
    

    如果你传递给函数的值是一个对象或数组,你可以变异它并且原始值也会被变异,因为Javascript中的对象和数组是通过引用传递的。

    function makeItTrue (value) {
      value.it = true
      console.log(value.it) // true
    }
    
    var myVariable = { it: false }
    makeTrue(myVariable)
    console.log(myVariable.it) // true
    

    换句话说,您需要改变context 参数而不是重新分配它。

    【讨论】:

    • 所以我要做的不是context = {location: data.location},而是context.location = newLocation,对吧?
    猜你喜欢
    • 2017-03-09
    • 2022-10-31
    • 2019-03-09
    • 2020-06-01
    • 2020-05-18
    • 2020-04-05
    • 2020-05-30
    • 2020-05-30
    • 2020-05-02
    相关资源
    最近更新 更多