图QL-工具:生成并模拟图QL.js计划
此软件包提供了创建 GraphQL 方案的若干有用方法:
- 使用 GraphQL 语法 生成一个方案 并全力支持解决者、界面、结合和定制的分级。 制作的图案完全兼容 图QL.js。 。 。 .
- 锁定您的图形QL API 与精细的每类嘲笑
- 自动 将多个计划缝合在一起 变成一个更大的 API
文档
装入 HTTP
如果您想要将您的 JavaScript GraphQL 计划绑定在一个 HTTP 服务器上, 我们建议使用 阿波罗服务器,它支持每个受欢迎的节点HTTP服务器库,包括Express,Koa,Hapi等.
JavaScript GraphQL 服务器通常与 graphql-tools 财务报告和审定财务报表 apollo-server-express 一起:一个是写出chema和解析器代码,另一个是把它连接到网络服务器上.
示例
使用时 graphql-tools,您将方案描述为 GraphQL 类型语言字符串 :
const typeDefs = `
type Author {
id: ID! # the ! means that every author object _must_ have an id
firstName: String
lastName: String
"""
the list of Posts by this author
"""
posts: [Post]
}
type Post {
id: ID!
title: String
author: Author
votes: Int
}
# the schema allows the following query:
type Query {
posts: [Post]
}
# this schema allows the following mutation:
type Mutation {
upvotePost (
postId: ID!
): Post
}
# we need to tell the server which types represent the root query
# and root mutation types. We call them RootQuery and RootMutation by convention.
schema {
query: Query
mutation: Mutation
}
`;
export default typeDefs;
然后定义解析器为嵌入对象,将类型和字段名称映射为解析器函数:
const resolvers = {
Query: {
posts() {
return posts;
},
},
Mutation: {
upvotePost(_, { postId }) {
const post = find(posts, { id: postId });
if (!post) {
throw new Error(`Couldn't find post with id ${postId}`);
}
post.votes += 1;
return post;
},
},
Author: {
posts(author) {
return filter(posts, { authorId: author.id });
},
},
Post: {
author(post) {
return find(authors, { id: post.authorId });
},
},
};
export default resolvers;
最后,将计划与解决者合并使用 makeExecutableSchema数字 :
import { makeExecutableSchema } from 'graphql-tools';
const executableSchema = makeExecutableSchema({
typeDefs,
resolvers,
});
此示例包含一个字符串中的整个类型定义, 以及一个文件中的所有解析器, 但是您可以将多个文件和对象中的类型和解析器组合起来, 如文件 模块化计划a 部分.
捐款
发言、问题和专题请求非常受欢迎。 如果您正在使用此软件包并为自己修复一个错误, 请考虑提交 PR !
维护者
- @hwillson (英语) (阿波罗
- @ 本贾姆 (阿波罗