graphql-kit / graphql-faker

🎲 Mock or extend your GraphQL API with faked data. No coding required.
MIT License
2.69k stars 225 forks source link

Sort by field #83

Closed LeeroyJenks closed 4 years ago

LeeroyJenks commented 4 years ago

Is there a way to pass a sortBy param and sort by an endpoint?

This may be too much of a stretch, but sometimes for testing purposes we want to get data sorted by name, time, or another value.

IvanGoncharov commented 4 years ago

@LeeroyJenks Not sure I understand your use case, can you please provide more details? If you mean field order in response: https://graphql.github.io/graphql-spec/draft/#sel-EAPJPDDAACFA_0O

Since the result of evaluating a selection set is ordered, the serialized Map of results should preserve this order by writing the map entries in the same order as those fields were requested as defined by query execution. Producing a serialized response where fields are represented in the same order in which they appear in the request improves human readability during debugging and enables more efficient parsing of responses if the order of properties can be anticipated.

LeeroyJenks commented 4 years ago

Sorry, I mean the returned data.

So if I have a definition like so:

type Consumer {
  name: String @fake(type: firstName)
}

type Query {
  consumer: [Consumer] @listLength(min: 3, max:5)
}

When I query it, I will get a random array, something like:

consumer: [
  { name: "Thomas" },
  { name: "Steve" },
  { name: "Jacob" }
]

Would I then be able to query it like:

consumer(sortBy: name, order: ASC) {
  name
}

And then get a response like:

consumer: [
  { name: "Jacob" },
  { name: "Steve" },
  { name: "Thomas" }
]
IvanGoncharov commented 4 years ago

@LeeroyJenks Thanks for providing more details. I think it's too specific to be handled by graphql-faker itself but I think it's an excellent use case to add middleware support into faker. For example:

export default const resolverWrappers = {
  Query: {
    async cosumer(source, args, ctx, info, next) {
      const consumers = await next(source, args, ctx, info);

      return consumers.slice().sort((consumer1, consumer2) => {
        return consumer1.name.localeCompare(consumer2.name);
      });
    }
  }
}

and run as graphql-faker --resolversJS ./customresolvers.js ... Note: It's just an example I brain storm in like 10m

@LeeroyJenks What do you think about this idea in general?

LeeroyJenks commented 4 years ago

That makes sense! Faker should only provide the data, and middleware can manipulate data accordingly if necessary. That keeps Faker simple and light.

knidarkness commented 4 years ago

@IvanGoncharov, if you think that would be good feature to have (middlewares) I could take a look and work on its implementation.