类型生成

使用 .model() 方法时,您会收到模型类的通用实例。但是,由于每个模型的返回值和参数取决于模式中的内容,因此无法提前知道每个类型是什么。相反,您可以使用 @neo4j/graphql 包中公开的 generate() 函数,每次更改模式时为您的模型生成 TypeScript 类型。

以下示例展示了如何从 @neo4j/graphql 导入 generate 函数,并添加一个条件分支来检查 process.env.GENERATE 变量是否已设置,如下所示

GENERATE="true" ts-node index.ts

然后,当您使用设置的变量运行此代码时,这些类型将变得可用,您可以将它们作为泛型导入和使用。以下是一个示例

import { OGM, generate } from "@neo4j/graphql-ogm";
import { ModelMap } from "./ogm-types"; // this file will be auto-generated using 'generate'
import * as neo4j from "neo4j-driver"
import * as path from "path"

const typeDefs = `
    type Movie {
        id: ID
        name: String
    }
`;

const driver = neo4j.driver(
    "bolt://localhost:7687",
    neo4j.auth.basic("username", "password")
);

// Generic is applied on the OGM
const ogm = new OGM<ModelMap>({ typeDefs, driver });

const Movie = ogm.model("Movie");

async function main() {
    // Only generate types when you make a schema change
    if (process.env.GENERATE) {
        const outFile = path.join(__dirname, "ogm-types.ts");

        await generate({
            ogm,
            outFile,
        });

        console.log("Types Generated");

        process.exit(1);
    }

    // Get full autocomplete on `Movie`, including where argument properties plus the return value
    const [theMatrix] = await Movie.find({ where: { name: "The Matrix" } });
}
main()