使用 TypeORM 实体的 GraphQL 查询

GraphQL query using TypeORM entity

我正在学习 graphql 并将其与 typeorm 相结合。我用 graphql 编写了一个查询,想知道这是否是将 typeorm 实体和同一实体的 graphql 类型结合起来的正确方法。或者有没有办法让我使用 typeorm 实体而不是 graphql 类型作为 return 值?

typeorm 实体和graphql 类型具有完全相同的字段,本质上是完全相同的。只有一个被定义为 graphql 类型,另一个使用 typeorm 装饰器。

我也不确定这种魔法是如何从 Promise<Test> 中 return 生成 TestType 的。 TestTypegraphql 类型,<Test>typeorm 实体。

import {GraphQLFieldConfig, GraphQLNonNull} from "graphql/type/definition";
import {TestType} from "../type/TestType";
import {GraphQLID} from "graphql";
import {IGraphQLContext} from "../IGraphQLContext";

export const Test: GraphQLFieldConfig<any, IGraphQLContext, any> = {
    // notice the type to return here is the graphql type
    type: new GraphQLNonNull(TestType),
    description: "A query for a test",
    args: {
        id: {
            type: new GraphQLNonNull(GraphQLID),
            description: "The ID for the desired test"
        }
    },
    async resolve (source, args, context) {
        // getTest(...) here returns a promise<Test> where Test is a typeorm entity
        return context.db.testDAO.getTest(args.id);
    }
};

我决定放弃使用 typeorm 的尝试,转而使用 Prisma

如果您正在寻找 Prisma 的魔力(自动生成的数据库和架构),以及托管 API 和访问模型和解析器以便执行自定义操作的灵活性,您应该查看Warthog. It’s a Node.js GraphQL API framework written in TypeScript where you set up resolvers and data models, and it auto-generates your entire schema with opinionated pagination, filtering, etc... similar to Prisma’s conventions. It’s not as feature-rich as Prisma, but it gives you a lot more control. You can check out warthog-starter,这会让你很快 运行。

免责声明:我是 Warthog 的作者