GraphQL,Apollo:创建有效的模式

时间:2018-12-09 11:00:37

标签: schema graphql apollo

我最近开始研究使用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 };

但这是效率低下的代码。如果漫画的类别增加,我应该继续添加查询。因此,我想提高“更多便利性和可读性”。

例如,我想管理漫画书中的Onepiece和Naruto类别。

我该如何改善?

1 个答案:

答案 0 :(得分: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进行任何其他更改模式或查询。