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