从现有 Neo4j 数据库中检视模式
|
这是 GraphQL Library 7 版本的文档。对于长期支持 (LTS) 版本 5,请参考 GraphQL Library 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://: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://: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();