获取通过GraphQL变异创建的新数据集的数据

时间:2017-11-07 11:20:09

标签: javascript graphql

我试图做一个突变。突变本身正在工作(用户是在DB中创建的), 但响应只有null个值:

data
  createUser:
    createdAt: null
    password: null
    username: null

我不知道,我做错了什么。我想我必须指定哪些数据我想要回来。 但是当我创建用户时,我不知道它的ID。那么如何将当前添加的数据集作为响应返回?

服务器/变异架构

const UserType = new GraphQLObjectType({
  name: 'user',
  fields: {
    _id: { type: GraphQLID },
    createdAt: { type: GraphQLString },
    username: { type: GraphQLString },
    password: { type: GraphQLString }
  }
})

const MutationType = new GraphQLObjectType({
  name: 'RootMutationType',
  description: 'Mutations',
  fields: () => ({
    createUser: {
      type: UserType,
      args: {
        username: { type: new GraphQLNonNull(GraphQLString) },
        password: { type: new GraphQLNonNull(GraphQLString) }
      },
      async resolve ({ db }, { username, password }) {
        return db.collection('users').insert({
          _id: Random.id(),
          createdAt: new Date(),
          username,
          password: bcrypt.hashSync(password, 10)
        })
      }
    }
  })
})

客户/组件

this.props.createUserMutation({
  variables: { username, password }
}).then(response => {
  console.log(response.data) // data has expected fields, but those have null value
})

// ...

export default compose(
  withData,
  withApollo,
  graphql(
    gql`
      mutation RootMutationQuery($username: String!, $password: String!) {
        createUser(
          username: $username,
          password: $password,
        ) {
          _id
          createdAt
          username
          password
        }
      }
    `, {
      name: 'createUserMutation'
    }
  )
)

2 个答案:

答案 0 :(得分:0)

我认为知道发生了什么事情会发现错误

所以更改此查询

this.props.createUserMutation({ variables: { username, password } }).then(response => { console.log(response.data) // data has expected fields, but those have null value })

this.props.createUserMutation({ variables: { username, password } }).then(response => { console.log(response.data) // data has expected fields, but those have null value }).catch(error => { console.error(error) })

答案 1 :(得分:0)

我没有使用meteor,但是查看文档,我认为你对insert的调用只返回id,而实际的db操作是异步完成的。

在这种特殊情况下,您在发送插入呼叫之前确定_idcreateAt的值,因此您拥有发送回客户端所需的所有信息。只是做:

resolve ({ db }, { username, password }) {
  const _id = Random.id()
  const createdAt = new Date()
  db.collection('users').insert({
    _id,
    createdAt,
    username,
    password: bcrypt.hashSync(password, 10)
  })
  return { _id, username, password, createdAt }
}

如果我们希望MongoDB为我们生成_id,我们可以从插入调用中省略它:

resolve ({ db }, { username, password }) {
  const createdAt = new Date()
  const _id = db.collection('users').insert({
    createdAt,
    username,
    password: bcrypt.hashSync(password, 10)
  })
  return { _id, username, password, createdAt }
}