簡體   English   中英

如何使用Apollo服務器對graphQl中的數據進行排序?

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

我使用apollo-server編寫graphql代碼。 在發送數據之前,我想基於可選字段和過濾器對數據進行某種排序,並且我需要知道編寫代碼的正確方法嗎? graphql中是否有一種方法可以自動對數據進行排序?

我用lodash的排序,我想以后我搜索我看到他們不優化PRISMA ,但我的數據是由另一個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}`);
});

graphql中有功能嗎?

不,沒有可能單獨使用graphql進行排序,排序或進行任何過濾。 您需要自己或使用ORM(創建一個執行此操作的方法)來實現排序,然后將該邏輯掛接到將執行您提供的resolver方法的resolver上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM