我正在使用GraphQL,Apollo Express和MongoDB和Mongoose建立一个小型博客。
目前,文章是按其ID提取的,访问者可以在此处浏览ID为“ 123”的文章:example.com/articles/123
相反,我想使用,因此访问者可以转到example.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!
}
`;
然后,在解析器中,只需检查是否提供或中的一个id
,slug
否则date
返回错误。
另一种选择是使用类似于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!
}
`;
第三种选择是设置一个单独的搜索查询,该查询可以返回几种类型:
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!
}
`;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句