有没有更优雅的方式而不是编写大量查询?

Is there a more elegant way instead of writing lots of queries?

我正在使用 GraphQL、Apollo Express 和 MongoDB 以及 Mongoose 构建一个小型博客。

目前,文章是通过其 ID 获取的,访问者可以浏览 ID 为“123”的文章:示例。com/articles/123

相反,我想使用 slugs,以便访问者可以查看示例。com/articles/same-article-as-above

到目前为止我的解析器:

import { gql } from 'apollo-server-express';

export default gql`
  extend type Query {
    articles: [Article!]
    article(id: ID!): Article
  }

  type Article {
    id: ID!
    slug: String!
    title: String!
    desription: String!
    text: String!
  }
`;

我可以再添加一个查询:

    articleBySlug(slug: String!): Article

这会很好用。但是,这对我来说看起来不是很优雅,我觉得我缺少一些基本的理解。每次我试图通过标题、文本、描述或其他任何方式获取文章时,我真的必须向我的解析器添加一个新查询吗?我最终会得到很多查询,例如 "articleByTitle"、"articleByDate" 等等。有人可以给我提示、示例或一些最佳实践吗(或者只是确认我确实必须添加越来越多的查询☺)?

一种常见的方法是将所有输入添加到同一个查询中,并使它们成为可选的:

export default gql`
  extend type Query {
    articles: [Article!]
    article(id: ID, slug: String, date: String, search: String): Article
  }

  type Article {
    id: ID!
    slug: String!
    title: String!
    description: String!
    text: String!
  }
`;

然后,在解析器中检查是否提供了 idslugdate 之一,如果没有提供 return 错误。

另一种选择是使用类似于 Gmail 使用的搜索字符串(例如 id:x before:2012-12-12),然后在解析器中进行解析。

export default gql`
  extend type Query {
    articles: [Article!]
    article(search: String): Article
  }

  type Article {
    id: ID!
    slug: String!
    title: String!
    description: String!
    text: String!
  }
`;

第三个选项是设置一个单独的搜索查询,可以 return 几种类型:

export default gql`
  extend type Query {
    articles: [Article!]
    search(query: String!, type: SearchType): SearchResult 
  }

  union SearchResult = Article | User

  enum SearchType {
    ARTICLE
    USER
  }

  type Article {
    id: ID!
    slug: String!
    title: String!
    description: String!
    text: String!
  }

  type User {
    id: ID!
    email: String!
    name: String!
  }
`;