自动为ArangoDB生成GraphQL
当前,使用GraphQL查询ArangoDB需要构建GraphQL.js模式。这很繁琐,并且生成的JavaScript模式文件可能很长且很庞大。
在这里,我们将演示概念的简短证明,该概念证明将与用户相关的部分简化为仅定义GraphQL IDL
文件和简单的AQL
查询。
介绍指令 @aql
。使用此指令,可以编写获取所需数据的AQL查询。使用bind参数 @current
,可以访问当前父对象以执行JOIN或相关操作。
GraphQL IDL
简单的查询
type Author {
_key: String!
name: String
}
type Query {
blogEntry(_key: String!): Author
}
该IDL描述了Author对象。Query类型定义了一个的查询BlogEntry。
现在让我们看一下GraphQL查询:
{
blogEntry(_key: "1") {
name
}
}
接下来使用@aql
type BlogEntry {
_key: String!
authorKey: String!
author: Author @aql(exec: "FOR author IN Author FILTER author._key == @current.authorKey RETURN author")
}
type Author {
_key: String!
name: String
}
type Query {
blogEntry(_key: String!): BlogEntry
}
该IDL描述了BlogEntry和Author对象。BlogEntry的Author其经由在该指令的AQL查询提取对象@aql。Query类型定义了一个的查询BlogEntry。
现在让我们看一下GraphQL查询:
{
blogEntry(_key: "1") {
_key
authorKey
author {
name
}
}
}
该查询获取BlogEntry带有_key=“ 1”的。生成的AQL查询为:
FOR doc IN BlogEntry FILTER doc._key == '1' RETURN doc
对于获取的BlogEntry文档,Author通过指令中定义的AQL查询获取相应的文档。
结果大致如下所示:
{
"data" : {
"blogEntry" : {
"_key" : "1",
"authorKey" : "2",
"author" : {
"name" : "annie"
}
}
}
}
使用GraphQL IDL可以减少用户使用GraphQL查询ArangoDB的工作量。对于简单的GraphQL查询和IDL,可以自动生成解析器以获取必要的数据。
产生npm包的工作称为graphql-aql-generator。
ArangoDB Foxx示例
现在,让我们看一个相同的示例,但使用ArangoDB javascript框架– Foxx。为此,我们必须遵循下面列出的简单步骤:
- 打开ArangoDB Web界面并导航到SERVICES。
- 然后点击Add Service。选择New Service并填写所有字段*。
- 重要的是Mount领域。我会用/test。然后生成。
单击该服务以打开其设置。单击Settings,然后转到以Set Development启用开发模式。 - 然后单击Info并在打开路径Path:。
现在我们必须安装npm软件包:
npm install --save graphql-aql-generator
我们还需要创建两个集合Author和BlogEntry。以及以下文件:
Author 集合:
{
"_key":"2"
"name": "annie"
}
BlogEntry 集合:
{
"_key":"1"
"authorKey": "2"
}
Foxx具有内置的 graphql
路由器,我们可以使用它来服务GraphQL查询。我们创建了一个称为的新路由 /graphql ,用于服务传入的GraphQL查询。通过graphiql: true
启用GraphiQL Explorer,可以测试驱动查询。
打开刚才下载的文档:在main.js 中进行修改;
// main.js code
'use strict';
const createRouter = require('@arangodb/foxx/router');
const router = createRouter();
module.context.use(router);
const createGraphQLRouter = require('@arangodb/foxx/graphql');
const generator = require('graphql-aql-generator');
const typeDefs = [`
type BlogEntry {
_key: String!
authorKey: String!
author: Author @aql(exec: "FOR author in Author filter author._key == @current.authorKey return author")
}
type Author {
_key: String!
name: String
}
type Query {
blogEntry(_key: String!): BlogEntry
}
`]
const schema = generator(typeDefs);
router.use('/graphql', createGraphQLRouter({
schema: schema,
graphiql: true,
graphql: require('graphql-sync')
}));
打开 127.0.0.1:8529/test/graphql
并加载GraphiQL资源管理器,因此我们可以执行查询以获取BlogEntry带有的查询Author。
{
blogEntry(_key: "1") {
_key
authorKey
author {
name
}
}
}
The result is:
{
"data": {
"blogEntry": {
"_key": "1",
"authorKey": "2",
"author": {
"name": "Author Name"
}
}
}
}