Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Apollo Client - useQuery - cómo establecer el parámetro como opcional

tengo esta consulta:

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

Fragmento del componente:

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

En backend, la consulta de graphQL el código es el siguiente:

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

tipoDef:

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

Mi pregunta es, si no se proporciona el nombre de username , la consulta no funciona, no devuelve nada, ¿cómo hacer que el nombre de usuario sea opcional? No lo configuré en la consulta como se requiere.

Mi solución actual es usar la resolución de consultas en consecuencia, sin embargo, no es realmente ideal en caso de que haya más parámetros opcionales.

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

Gracias.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El nombre de username es opcional en la definición de su esquema. La razón por la que no recibes nada es porque el nombre de usuario no está definido cuando no se proporciona; por lo que el filtro no puede encontrar nada para devolver.

Esto debería funcionar:

 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') } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!