Search code examples
javascriptgraphqltypeorm

GraphQL query using TypeORM entity


I am learning graphql and combining it with typeorm. I wrote a query with graphql and was wondering if this is the correct way to combine the typeorm entity and the graphql type for the same entity. Or is there a way for me to use the typeorm entity instead of the graphql type as the return value?

The typeorm entity and the graphql type have the exact same fields, essentially the are exactly the same. Just one is defined as a graphql type and the other is using the typeorm decorators.

I am also not sure how this magic is returning a TestType from a Promise<Test>. Where TestType is a graphql type and <Test> is a typeorm entity.

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);
    }
};

Solution

  • I decided to ditch the attempt to use typeorm and went with Prisma.