api工具 graphql_如何使用GraphQL API进行数据库管理

api工具 graphql

by Michael Hunger

迈克尔·汉格(Michael Hunger)

如何使用GraphQL API进行数据库管理 (How you can use a GraphQL API for database administration)

A recent discussion at graphql-europe made me realize that GraphQL would make for an amazing API for database administration.

最近在graphql-europe上进行的讨论使我意识到GraphQL将为数据库管理提供出色的API。

You know that plethora of functions and options to control details from security, indexing, metadata, clustering, and other operations?

您知道过多的功能和选项可以控制来自安全性,索引编制,元数据,群集和其他操作的详细信息吗?

I used the trip home on the train to build a GraphQL admin endpoint for Neo4j, exposing all available procedures either as queries or mutations. Using Kotlin, this was fortunately a matter of only a few lines (200) of code. And it worked surprisingly well.

我在火车上回家旅行时,为Neo4j构建了GraphQL管理端点,将所有可用过程公开为查询或变异。 幸运的是,使用Kotlin,只需几行(200)代码即可。 而且效果惊人。

If you know of any other database that exposes its admin-API via GraphQL, please let me know in the comments — I’d love to have a look.

如果您知道其他任何通过GraphQL公开其admin-API的数据库,请在评论中让我知道-我很乐意看一下。

And if you get inspired to base some of your work on this idea, I’d be honored, even more so with attribution :)

而且,如果您受到启发将您的一些工作基于该想法,那么我将很荣幸,甚至归功于此:)

TL; DR (TL;DR)

You can get your Neo4j Admin API served at /graphql/admin by installing the lastest version of the neo4j-graphqlextension. In Neo4j Desktop just click "Install GraphQL" in the Plugins section of your database (version 3.4.0.1). You might need to configure a basic auth header for your database user’s credentials. Then you’re ready to query your new and shiny Admin API via GraphiQL or GraphQL Playground.

通过安装最新版本的neo4j-graphql扩展,可以在/graphql/admin获得Neo4j Admin API的服务。 在Neo4j Desktop中,只需在数据库( version 3.4.0.1 )的“插件”部分中单击“安装GraphQL”。 您可能需要为数据库用户的凭据配置基本的auth标头 。 然后,您就可以通过GraphiQL或GraphQL Playground查询新的闪亮的Admin API。

The endpoint is not limited to built-in procedures. External libraries like APOC, graph-algorithms, or neo4j-spatial are automatically exposed.

端点不限于内置过程。 诸如APOC,图算法或neo4j-spatial之类的外部库会自动公开。

好处 (Benefits)

In my book, the biggest benefit is the self documenting nature of GraphQL APIs based on the strict schema provided.

在我的书中,最大的好处是基于所提供的严格模式的GraphQL API的自我记录性质

The strong typing, documentation, and defaults for both input and output types increase the clarity and reduce the number of trial-and-error attempts. The custom selection of output fields and optional deeper traversal of result structures allows for quick customizations of what you want to retrieve.

输入和输出类型的强类型,文档和默认值提高了清晰度,并减少了反复试验的次数。 自定义输出字段的选择以及对结果结构的更深入遍历(可选),可以快速自定义要检索的内容。

With the clear separation into read queries and write mutations, it is easy to reason about the impact of a call.

由于清楚地将读取查询和写入突变分开 ,因此很容易推断出调用的影响。

And of course the amazing auto-complete with inline help and the automatically available documentation in GraphiQL and GraphQL-Playground make interacting with such an API a joy. ?

当然, 带有内联帮助惊人的自动完成功能以及GraphiQL和GraphQL-Playground中自动提供的文档也使与此类API进行交互变得很有趣。 ?

Parameterizing all inputs and limiting result sizes is just icing on the ?.

参数化所有输入并限制结果大小只是锦上添花。

Another advantage is that you can combine multiple queries into a single call. All relevant information for a full screen is retrieved in a single request.

另一个优点是您可以将多个查询合并到一个调用中。 在单个请求中检索全屏的所有相关信息。

Of course you can use all the available GraphQL tools like middleware or libraries for quickly building front-end applications (apollo-tools, React, semantic-ui, victory, etc.). That allows you to integrate these APIs quickly into your monitoring/administration scripts or dashboards.

当然,您可以使用所有可用的GraphQL工具(例如中间件或库)来快速构建前端应用程序(Apollo工具,React,语义UI,胜利等)。 这样,您就可以将这些API快速集成到监视/管理脚本或仪表板中。

实施细节 (Implementation Details)

Like the regular GraphQL endpoint in neo4j-graphql, this is a server extension serving GET, POST, and OPTIONS endpoints. They take in queries, variables and operation names to execute within a single transaction. After execution, the results or errors are returned as JSON to the client.

neo4j-graphql的常规GraphQL端点neo4j-graphql ,这是一个服务于GET,POST和OPTIONS端点的服务器扩展。 它们接受查询变量操作名称以在单个事务中执行。 执行后, 结果错误将作为JSON返回给客户端。

The necessary graphql-schema is built from the available user-defined-procedures deployed in Neo4j.

必要的graphql模式是根据Neo4j中部署的可用用户定义过程构建的。

You have to explicitely allow procedures to be exposed via the config setting graphql.admin.procedures.(read/write) with either Neo4j procedure syntax or admin-endpoint field names. For example, you could set it to:

您必须明确地允许使用Neo4j过程语法或管理端点字段名称通过配置设置graphql.admin.procedures.(read/write)公开过程。 例如,您可以将其设置为:

graphql.admin.procedures.read=db.*,dbms.components,dbms.queryJ*graphql.admin.procedures.write=db.create*,dbIndexExplicitFor*
用户定义的过程 (User Defined Procedures)

In 2016, Neo4j 3.0 got a neat new extension point. You could provide annotated Java methods as user defined procedures, which then were callable either stand-alone or as part of your database queries. As our (React-based) Neo4j-Browser moved from HTTP to a binary transport, the original management REST-APIs were augmented with procedures providing the same functionality.

2016年,Neo4j 3.0有了一个全新的扩展点。 您可以提供带注释的Java方法作为用户定义的过程,然后可以将其独立或作为数据库查询的一部分进行调用。 随着我们的(基于响应的)Neo4j-Browser从HTTP转移到二进制传输,原始的管理REST-API通过提供相同功能的过程得到了增强。

Each procedure can take parameters and returns a stream of data with individually named columns, similar to regular query results. Both inputs and outputs can use data types from the Cypher type system.

每个过程都可以获取参数,并返回具有单独命名的列的数据流 ,类似于常规查询结果。 输入和输出都可以使用Cypher类型系统中的数据类型。

call dbms.listConfig('dbms.connector.http')   yield name, value, description;
╒══════════════════════════════╤═══════╤════════════════════════╕│"name"                        │"value"│"description"           │╞══════════════════════════════╪═══════╪════════════════════════╡│"dbms.connector.http.enabled" │"true" │"Enable this connector."│├──────────────────────────────┼───────┼────────────────────────┤│"dbms.connector.https.enabled"│"true" │"Enable this connector."│└──────────────────────────────┴───────┴────────────────────────┘

Ever since, a large amount of functionality has been moved to procedures and functions, giving us a broad selection of things to expose via GraphQL.

从那时起,大量的功能已转移到过程和函数中,使我们可以通过GraphQL公开多种选择。

To construct the schema, I iterated over the available procedures, creating one field for each procedure.

为了构造模式,我遍历了可用的过程,为每个过程创建一个字段

I took the named procedure parameters as input arguments and used custom output types (per procedure) holding the returned columns. Input parameters with default values could be nullable, the others are defined as non-null. Procedure descriptions turned into field descriptions, and the deprecation information was also transferred.

我将命名过程参数作为输入参数,并使用自定义输出类型 (每个过程)来保存返回的列。 具有默认值的输入参数可以为null ,其他参数则定义为非null。 过程描述变成了字段描述 ,并且弃用信息也已传输。

I mapped basic scalar types and lists directly to GraphQL types.

我将基本标量类型和列表直接映射到GraphQL类型。

Only for the Map (dict/object) type did I have to map to a List<Attribute> where each attribute is

仅对于Map (字典/对象)类型,我才必须映射到List<Attribu te>,其中每个属性是

type Attribute {   name: String!   value: String   type: String!  = "String"}

which worked suprisingly well both for inputs and outputs.

在输入和输出方面都表现出色。

Similarly, I created custom types for Node, Relationship and Path.

同样,我为NodeRelationshipPath创建了自定义类型。

For these four custom types, I added the appropriate (de-)serialization code. All other unknown types were rendered to strings.

对于这四种自定义类型,我添加了适当的(反序列化)代码。 所有其他未知类型都呈现为字符串。

The resolver for each field just executes the wrapped procedure with the input arguments from the environment. The results are then mapped to the output type fields (optionally transformed) and returned to the endpoint.

每个字段的解析程序仅使用来自环境的输入参数执行包装的过程 。 然后将结果映射到输出类型字段(可选转换)并返回到端点。

Based on their metadata, I combined the fields into object types for Queries and Mutations, respectively.

根据它们的元数据,我将字段分别组合为查询和突变的对象类型。

And that was basically it.

基本上就是这样。

I was surprised myself when I fired up GraphiQL after deploying the extension that I was able to intuitively call any of the queries and mutations without hiccups.

当我部署扩展程序后启动了GraphiQL时,我感到很惊讶,我能够直观地调用任何查询和变异而不会打h。

挑战性 (Challenges)

My biggest challenge is the lack of namespaces in GraphQL. While you can substructure queries nicely with nested types, the same is not available for mutations.

我最大的挑战是GraphQL中缺少名称空间 。 虽然您可以使用嵌套类型很好地对查询进行子结构化,但对于突变而言则无法使用相同的结构。

To keep the API naming consistent across both, I decided not to substructure queries and like mutations, and instead joined the capitalized parts of the namespace and procedure name together.

为了使API命名在两者之间保持一致,我决定不对子结构进行查询, 也不喜欢进行突变,而是将名称空间的大写部分和过程名称结合在一起。

So db.labels turns into dbLabels .

因此db.labels变成dbLabels

Another slight challenge was the missing information about read vs. write operations in the DBMS and SCHEMA scopes of Neo4j procedures. So I had to use a whitelist to determine "read-only" ones, which of course is not sufficient.

另一个小挑战是Neo4j过程的DBMSSCHEMA范围中缺少有关读写操作的信息。 因此,我不得不使用白名单来确定“只读” 名单 ,这当然是不够的。

知名人士 (Notables)

Something that other API technologies don’t have built in, and which is really cool, is the ability to choose and pick any number of queries or mutations you want to run in a single request.

其他API技术没有内置的功能,这真的很酷,它能够选择并选择要在单个请求中运行的任意数量的查询或变异。

If necessary, you can even alias multiple invocations of the same query with different parameters (think statistics per database).

如有必要,您甚至可以使用不同的参数为同一查询的多个调用添加别名(请考虑每个数据库的统计信息)。

And you can even run graph-algorithms or cypher statements as part of this API, which is kinda cool.

您甚至可以将图形算法或密码语句作为此API的一部分运行,这很酷。

下一步 (Next Steps)

Currently, I only directly expose the procedures parameters and results to the users. Going forward, it would be nice to derive higher level types that offer their own (dynamic) query fields, like

目前,我仅直接向用户公开过程参数和结果。 展望未来,最好派生提供自己(动态)查询字段的高级类型,例如

  • a Label type that also can return counts

    标签类型也可以返回计数
  • a Server type that can provide its cluster role or other local information

    可以提供其群集角色或其他本地信息的服务器类型
  • adding more dynamic fields with parameters on a Node or Relationship type for custom traversals

    在节点或关系类型上添加带有参数的更多动态字段以进行自定义遍历

I would love ? a bunch of monitoring and management mobile-, web-apps and command-line-clients to be built on top of this management API.

我喜欢 ? 一堆米onitoring和管理mobile-,网络应用程序和命令行的客户端的待建对T的顶他的管理API。

I’m excited to see where we could improve the usability and what feedback and requests we get. Of course the first target would a graph-app for Neo4j Desktop. So if you’re interested in any of this, please reach out and let’s chat.

我很高兴看到我们可以在哪里改善可用性,以及我们收到了什么反馈和要求。 当然,第一个目标是Neo4j Desktopgraph-app 。 因此,如果您对此感兴趣, 请联系并开始聊天

Happy hacking! — Michael

骇客入侵! -迈克尔

If you run into any problems, please add a comment or raise a GitHub issue.

如果您遇到任何问题,请添加评论或提出GitHub问题

翻译自: https://www.freecodecamp.org/news/using-a-graphql-api-for-database-administration-1a5039b43c8f/

api工具 graphql

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值