How To Sort Data In GraphQl With Apollo Server?

- 1 answer

I use apollo-server to write a graphql code. before send data I want to do some sort on data based on optional fields and filters, and I need to know right way to write my code? Is there a method in graphql to automatically sort my data?

I used lodash for sort and I think they are not optimized after I searched I saw prisma but my data is returned by another api not in database. I need somthing like prisma.

my code something like this I want to sort book base on name or lastName in query but in real book objects returned by an api.

const { ApolloServer, gql, } = require('apollo-server');

const books = [
    title: 'Harry Potter and the Chamber of Secrets',
    authors: [{"name":"a1", "lastName":"aa1"},{"name":"b1", "lastName":"bb1"},{"name":"c1", "lastName":"cc1"}]
    title: 'Jurassic Park',
    authors: [{"name":"a" ,"lastName":"aa"},{"name":"b", "lastName":"bb"},{"name":"c", "lastName":"cc"}]
const typeDefs = gql`

type Book {
    title: String
    authors: [Author]
type Query{
    books: [Book]
type Author{
name: String
lastName: String
const resolvers = {
    books: () => books,
// in real this book return by an api !

const server = new ApolloServer({ typeDefs, resolvers });

server.listen({port: 3002, path: '/graphql'}).then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);

Is there a function In graphql?



No, there is no possibilities to sort, order, or to do whatever filtering with graphql alone. You need to implement the sorting by yourself or with a ORM (make a method that does that), then hook that logic on a resolver that will execute the resolver method that you provided.