简体   繁体   English

如何使用Apollo服务器对graphQl中的数据进行排序?

[英]How to sort data in graphQl with apollo server?

I use apollo-server to write a graphql code. 我使用apollo-server编写graphql代码。 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? graphql中是否有一种方法可以自动对数据进行排序?

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. 我用lodash的排序,我想以后我搜索我看到他们不优化PRISMA ,但我的数据是由另一个API不在数据库中返回。 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. 我的代码是这样的,我想根据查询中的name或lastName对书进行排序,但要根据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 = {
  Query: 
  {
    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? graphql中有功能吗?

No, there is no possibilities to sort, order, or to do whatever filtering with graphql alone. 不,没有可能单独使用graphql进行排序,排序或进行任何过滤。 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. 您需要自己或使用ORM(创建一个执行此操作的方法)来实现排序,然后将该逻辑挂接到将执行您提供的resolver方法的resolver上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM