【问题标题】:GraphQL, Apollo : Creating an efficient schemaGraphQL,Apollo:创建高效的模式
【发布时间】:2019-05-10 12:33:49
【问题描述】:

我最近开始学习使用 GraphQL 和 Apollo 进行服务器开发。 在下面的代码中,获取每个数据的公式有点好理解。

schema.js

const { gql } = require('apollo-server');
const _ = require('lodash');

const onepieces = [
  {
    "id": "onepiece1",
    "title": "원피스 1권",
    "price": "1,360",
    "desc": "동터오는 모험의 시대"
  },
  {
    "id": "onepiece2",
    "title": "원피스 2권",
    "price": "1,360",
    "desc": "대결 버기 해적단"
  }
];
const narutos = [
  {
    "id": "naruto1",
    "title": "나루토 1권",
    "price": "1,360",
    "desc": "나루토 모험의 시작"
  },
  {
    "id": "naruto2",
    "title": "나루토 2권",
    "price": "1,360",
    "desc": "나루토와 안개마을"
  }
];

const typeDefs = gql`  
    type Onepiece { id: ID, title: String, price: String, desc: String }
    type Naruto { id: ID, title: String, price: String, desc: String }

    type Query {
        onepiece(id: String!): Onepiece,
        naruto(id: String!): Naruto,
        getOnepieces: [Onepiece],
        getNarutos: [Naruto]
    }
`;

const resolvers = {
  Query: {
    onepiece: (parent, args) => _.find(onepieces, {id: args.id}),
    naruto: (parent, args) => _.find(narutos, {id: args.id}),
    getOnepieces: () => onepieces,
    getNarutos: () => narutos
  }
};

module.exports = { typeDefs, resolvers };

但这是低效的代码。如果漫画书的类别增加了,我应该继续添加查询。所以我想改进更方便和可读。

例如,我想管理 Comic Book 中的 Onepiece 和 Naruto 类别。

我该如何改进?

【问题讨论】:

    标签: schema graphql apollo


    【解决方案1】:

    您可以从编写可能类别的 GraphQL 枚举开始。

    enum Category { ONEPIECE NARUTO }
    

    由于两种漫画书具有相同的结构,您可以使用一个 GraphQL 类型来表示它们。我们将合并我们刚刚编写的类别,以便您分辨哪个是哪个。

    type ComicBook implements Node {
      id: ID!
      category: Category!
      title: String!
      price: String!
      desc: String!
    }
    

    有一个有点标准的convention for retrieving arbitrary GraphQL objects by their ID;虽然它来自 Facebook 的 Relay Javascript 客户端,但它并没有专门与该客户端绑定,我会在这里使用它。

    interface Node {
      id: ID!
    }
    type Query {
      node(id: ID!): Node
    }
    

    这将替换您的顶级查询,以按 ID 检索特定种类的书籍;你可以写一个类似的查询

    {
      node(id: "naruto1") {
        ... on ComicBook { category title price desc }
      }
    }
    

    现在您有了类别枚举,您还可以编写一个顶级查询来返回可能按类别过滤的漫画书

    type Query {
      comicBooks(category: Category): [ComicBook!]!
    }
    
    {
      comicBooks(category: ONEPIECE) { id title price desc }
    }
    

    有一些相应的代码更改以使其工作;我可能会先将两个漫画书列表合并为一个,然后在其中添加一个类似的类别字段。

    完成此操作后,如果添加第三个类别,则需要将其添加到枚举中并将其添加到数据集中,但您不需要对代码 GraphQL 进行任何其他更改架构或查询。

    【讨论】:

    • 谢谢!我会尝试这种方式^^
    猜你喜欢
    • 2019-03-01
    • 2019-04-22
    • 2018-04-23
    • 2019-12-28
    • 2021-11-28
    • 2020-12-21
    • 2011-12-23
    • 2018-09-27
    • 2018-06-23
    相关资源
    最近更新 更多