Я делаю приложение по аренде автомобилей, чтобы улучшить себя. .../перечисляет адреса транспортных средств, у меня есть 5 входов для выбора на левой боковой панели. Если значение выбрано, я хочу, чтобы у него был фильтр, если оно не выбрано, я хочу, чтобы у него не было фильтра. Я не мог структурировать, как отправить запрос и данные. Вы можете помочь мне?
subscription Vehicles($daily_price: String) {
vehicles(where: { _or: { daily_price: $daily_price, fuel: {}, gear: {}, model_id: {}, brand_id: {} } }) {
id
fuel
}
const { data, loading, error } = useSubscription(from && to ? VEHICLES_BY_DATE_RANGE : VEH_SUBS, {
variables: {
...filters,
},
});
Я знаю, что неправильно объяснил свою проблему. Я решил это так, возможно, вы сможете понять, посмотрев на это:
const createQuery = (filters: any) => {
const filterConditions = [];
if (filters?.brand_id) filterConditions.push(`brand_id : {_eq: "${filters.brand_id}"}`);
if (filters?.fuel) filterConditions.push(`fuel: {_eq: "${filters.fuel}"}`);
let q;
if (filterConditions.length > 0) {
q = `
{
_or: {${filterConditions.join(", ")}}
}
`;
} else q = "{}";
return gql`
subscription getVehicles {
vehicles(where: ${q}) {
model {
name
}
}
}
`;
};
const q = createQuery(filters);
const { data: d, loading: l, error: e } = useSubscription(q);
Я очень благодарен вам за ваш интерес, но был бы признателен, если бы вы поняли проблему и объяснили другое решение.
Хорошо, вот набросок того, как работать с переменными. Объявление типа основано только на том, что я считаю правильным на основе ваших фрагментов кода, поэтому вам, возможно, придется их настроить.
// I'm skipping the definition of how the Where filters, so here's just the query:
const VEH_SUBS = gql`
subscription getVehicles($where: Where!) {
vehicles(where: $where) {
model {
name
}
}
}`;
// I'm assuming the type of the filters based on your code snippets. They could be wrong (e.g. brand_id could be a number).
const createQuery = (filters: { brand_id?: string, fuel?: string, }) => {
// I'm assuming the type of the filterConditions based on your code snippets. It's probably not complete.
const filterConditions: {
where: { _or: { brand_id?: { _eq?: string }, fuel?: { _eq?: string } } }
} = { where: { _or: {} } };
// Setup filterConditions. Ofc, this could be done direclty in the line above, but I keep it separate so it might be easier to follow.
if (filters?.brand_id) filterConditions.where._or.brand_id = { _eq: filters.brand_id };
if (filters?.fuel) filterConditions.where._or.fuel = { _eq: filters.fuel };
const { data: d, loading: l, error: e } = useSubscription(
VEH_SUBS, // This should be a query which accepts where as argument!
{ variables: {where: filterConditions }}
);
...
};
Опять же, я рекомендую вам использовать graphql-codegen вместо явного предположения типа, как я, а также вместо any
, как вы.