wesleyyoung / perch-query-builder

Dynamically build TypeORM queries based on GraphQL queries for NestJS and TypeORM
GNU General Public License v3.0
46 stars 9 forks source link

Feature request: Support for GraphQL unions #15

Open Migushthe2nd opened 3 years ago

Migushthe2nd commented 3 years ago

Is your feature request related to a problem? Please describe. I have a GraphQL model that uses a union type, however, TypeORM entities do not support this kind of relation. To make this work, my TypeORM entity has two OneToMany relations and a getter that combines them. This way I can cast my ItemsEntity to ItemsModel

The classes are somewhere along the lines of:

export const ItemEntriesUnion = createUnionType({
    name: "ItemEntries",
    types: () => [ImageModel, BookModel],
    resolveType(value) {
        if (value instanceof ImageEntity) return ImageModel;
        if (value instanceof BookEntity) return BookModel;
    },
});

@ObjectType()
export class ItemsModel {
    @Field(() => [ItemEntriesUnion])
    items: Array<typeof ItemEntriesUnion>;
}

@Entity()
export class ItemsEntity extends BaseEntity  {
    @PrimaryColumn()
    id: string;

    @OneToMany(() => ImageEntity)
    images: ImageEntity[];

    @OneToMany(() => BookEntity)
    books: BookEntity[];

    get items() {
        return [...(this.images || []), ...(this.books || [])];
    }
}

Describe the solution you'd like I honestly have no idea what would be an acceptible solution.

Describe the solutions you've considered Say my graphql query is like this:

query {
  item(id: "1") {
    description
    entries {
      ... on BookModel {
        id
      }
    }
  }
}
  1. Perhaps some parameter in generateQueryBuilder(): mapFragments: [{fragment: string, mapTo: string}] For example

    {mapFragments: [{fragment: "entries.BookModel", mapTo: "books"}]
  2. A replacement for the NestJS createUnionType() that has an extra option argument typesMap: [{"BookModel": "books"}]

Additional context More info about the Union functionality can be found here Currently, if an enum is detected, this line errors: "parent.properties.type.getFields is not a function" https://github.com/wesleyyoung/perch-query-builder/blob/3b4bebfc04a8909420e0cad779e0294403bcca7e/src/functions/build-tree.ts#L31