graphql-compose / graphql-compose-mongoose

Mongoose model converter to GraphQL types with resolvers for graphql-compose https://github.com/nodkz/graphql-compose
MIT License
709 stars 94 forks source link

Can't filter response by fields #398

Closed lfaz closed 2 years ago

lfaz commented 2 years ago

I am trying to use the pagination plugin to list out the items and I have following code

schemaComposer.Query.addFields({
  vehicleById: VehicleTC.mongooseResolvers.findById(),
  vehicleByIds: VehicleTC.mongooseResolvers.findByIds(),
  vehicleOne: VehicleTC.mongooseResolvers.findOne(),
  vehicleTotal: VehicleTC.mongooseResolvers.count(),
  vehicleConnection: VehicleTC.mongooseResolvers.connection(),
  vehiclePagination: VehicleTC.mongooseResolvers
    .pagination()
    .addFilterArg({
      name: "priceFrom",
      type: "Int",
      description: "Search by price greater or equal than x",
      query: (rawQuery, value) => {
        rawQuery.price = { $gte: value };
      },
    })
    .addFilterArg({
      name: "priceTo",
      type: "Int",
      description: "Search by price less or equal than x",
      query: (rawQuery, value) => {
        rawQuery.price = { $lte: value };
      },
    }),
});

And I try to use it like:

"filter": {
    "priceFrom": 4,
    "priceTo": 5
  },

it doesnt seem to work, it only takes in consideration the first field priceFrom, any idea how to fix this? It should be pretty simple condition imo.

Also tried to do like which didnt work at all

"filter": {
    "AND": [
      {
         "priceFrom": 4,
         "priceTo": 5
      }
    ]
  },
lfaz commented 2 years ago

Also trying something like which still cant make it work:

.addFilterArg({
    name: "priceRange",
    type: `input priceRange {
        priceFrom: Float!
        priceTo: Float!
      }`,
    description: "Search by price greater or equal than x",
    query: (rawQuery, value) => {
      rawQuery.price = {
        $and: [{ $gte: value.priceFrom }, { $lte: value.priceTo }],
      };
    },
  }),
yurtaev commented 2 years ago

Try to activate mongoose.set('debug', true) and check raw query.

lfaz commented 2 years ago

in fact I managed to solve this out from this https://github.com/graphql-compose/graphql-compose/issues/22, there is a InputRange min,max example that seem to work pretty nice. I guess I will just close this issue!

lfaz commented 2 years ago

My final solution that seem to work:

name: "PriceRange",
type: `input priceRange {
        min: Float
        max: Float
      }`,
query: (rawQuery, value, resolveParams) => {
      let minPrice = value.min || 0;
      let maxPrice = value.max || 0;
      if (!minPrice && !maxPrice) return;
      if (minPrice > maxPrice && minPrice && maxPrice)
        [minPrice, maxPrice] = [maxPrice, minPrice];
      rawQuery.price = {};
      if (minPrice) {
        rawQuery.price.$gte = minPrice;
      }
      if (maxPrice) {
        rawQuery.price.$lte = maxPrice;
      }
    },