Apollo Client - useQuery - 如何将参数设置为可选

Apollo Client - useQuery - how to set parameter as optional

我有这个查询:

const CURRENT_MONTH_BY_USER = gql`
  query getCurrentMonthByUser($selectedMonth: String!, $username: String) {
    getCurrentMonthByUser(selectedMonth: $selectedMonth, username: $username) {
      id
      itemDate
      itemName
      itemCategory
      itemPrice {
        price
        currency
      }
      itemUpdated {
        isUpdated
        updatedBy
        updateStamp
      }
      createdBy {
        username
        name
        date
      }
    }
  }
`

来自组件的代码段:

  const result = useQuery(CURRENT_MONTH_BY_USER, {
    variables: { selectedMonth, username },
  })

后端,graphQL查询代码如下:

    getCurrentMonthByUser: async (_, args) => {
      try {
        const allItems = await Item.find({})

        const items = allItems
          .filter(item => item.itemDate.substring(0, 7) === args.selectedMonth)
          .filter(item => item.createdBy.username === args.username)

        return items
      } catch (err) {
        throw new Error('Specific month not found')
      }
    }

typeDef:

  type Query {
    getCurrentMonthByUser(selectedMonth: String!, username: String): [Item]
  }

我的问题是,如果没有提供username,查询不工作,returns没有,如何使用户名可选?我没有按要求在查询中设置。

我目前的解决方法是相应地使用查询解析器,但是如果有更多可选参数,这并不是很理想

    getCurrentMonthByUser: async (_, args) => {
      try {
        const allItems = await Item.find({})
        let items = []
        if (args.username) {
          items = allItems
            .filter(item => item.itemDate.substring(0, 7) === args.selectedMonth,)
            .filter(item => item.createdBy.username === args.username)
          return items
        }

        items = allItems.filter(
          item => item.itemDate.substring(0, 7) === args.selectedMonth,
        )
        return items
      } catch (err) {
        throw new Error('Specific month not found')
      }
    },

谢谢。

username 在您的架构定义中是可选的。您没有得到任何回报的原因是因为未提供用户名时未定义;所以过滤器找不到 return.

的任何内容

这应该有效:

    getCurrentMonthByUser: async (_, args) => {
      try {
        const allItems = await Item.find({})

        const items = allItems
          .filter(item => item.itemDate.substring(0, 7) === args.selectedMonth)
          .filter(item => args.username ? item.createdBy.username === args.username : true)

        return items
      } catch (err) {
        throw new Error('Specific month not found')
      }
    }