从现有 Neo4j 数据库中内省模式
这是 GraphQL 库版本 6 的文档。对于长期支持 (LTS) 版本 5,请参阅 GraphQL 库版本 5 LTS。 |
通过一个单独的 npm 包 @neo4j/introspector
,Neo4j 提供了一个工具,该工具能够从现有数据库生成 GraphQL 类型定义。这通常是一次性操作,应被视为 GraphQL 模式的一个起点。
@neo4j/introspector
完全支持生成类型定义,包括
-
一个
@relationship
指令,包括关系属性。 -
一个
@node
类型,具有以下功能:-
label
用于映射节点标签可能使用 GraphQL 支持字符集中不存在的字符的情况。 -
additionalLabels
用于具有多个标签的节点。
-
-
GraphQL 类型定义的只读版本。
如果元素属性在整个图中具有混合类型,则该属性将从生成的类型定义中排除。原因是,如果您的 GraphQL 服务器发现与指定类型不匹配的数据,它将引发错误。 |
如果跳过了任何属性,则会在 调试日志 中进行说明。
使用示例
您可以使用编程 API 来内省 Neo4j 模式并生成 GraphQL 类型定义。以下是一些您可能遇到的场景。
内省并持久化到文件
此示例内省数据库模式,生成 GraphQL 类型定义并将它们持久化到文件 schema.graphql
中。然后,您可以使用 GraphQL 服务器提供此文件。
import { toGraphQLTypeDefs } from "@neo4j/introspector";
import fs from "fs";
import neo4j from "neo4j-driver";
const driver = neo4j.driver(
"neo4j://localhost:7687",
neo4j.auth.basic("username", "password")
);
const sessionFactory = () => driver.session({ defaultAccessMode: neo4j.session.READ })
// We create a async function here until "top level await" has landed
// so we can use async/await
async function main() {
const typeDefs = await toGraphQLTypeDefs(sessionFactory)
fs.writeFileSync('schema.graphql', typeDefs)
await driver.close();
}
main()
内省并启动只读模式
此示例从数据库生成模式的**只读**版本,并立即启动一个 Apollo 服务器。在此,类型定义永远不会持久化到磁盘。
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from '@apollo/server/standalone';
import { Neo4jGraphQL } from "@neo4j/graphql";
import { toGraphQLTypeDefs } from "@neo4j/introspector";
import neo4j from "neo4j-driver";
const driver = neo4j.driver(
"neo4j://localhost:7687",
neo4j.auth.basic("username", "password")
);
const sessionFactory = () =>
driver.session({ defaultAccessMode: neo4j.session.READ });
// We create a async function here until "top level await" has landed
// so we can use async/await
async function main() {
const readonly = true; // We don't want to expose mutations in this case
const typeDefs = await toGraphQLTypeDefs(sessionFactory, readonly);
const neoSchema = new Neo4jGraphQL({ typeDefs, driver });
const server = new ApolloServer({
schema: await neoSchema.getSchema(),
});
await startStandaloneServer(server, {
context: async ({ req }) => ({ req }),
});
}
main();