簡體   English   中英

獲取通過GraphQL突變創建的新數據集的數據

[英]Get data of new dataset, which is created via GraphQL mutation

我正在嘗試做一個突變。 突變本身正在起作用(用戶是在數據庫中創建的),但是響應僅具有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'
    }
  )
)

我認為應該知道發生了什么錯誤

所以改變這個查詢

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) })

我沒有使用過流星,但查看文檔,我認為您的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 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM