Search code examples
graphqlnestjsapollomikro-orm

Make Mikro-ORM relational fields optional


I am using mikro-orm to generate graphql schemas and all fields in my One to One relationship are coming back required. How do I get them to be optional so that my query doesn't throw an error when a field comes back null? Here is how I am defining the relationship in ticket.entity.ts

@Field(() => Order, { nullable: true })
  @OneToOne(() => Order, null, { nullable: true })
  public order?: Order;

In my generated tickets.schema.graphql, the Order object returns this:

type Order {
  id: ID!
  createdAt: DateTime!
  updatedAt: DateTime!
  archivedAt: DateTime
  client: String!
  soldDate: DateTime!
  type: String!
  ...
  ...
  ...
}

In my Order entity, all fields are optional, and the generated SQL table understands them as such.

export class Order extends BaseEntity {
  @Field(() => String)
  @Property({ nullable: true })
  public client: string;

  @Field(() => Date)
  @Property({ columnType: "date", nullable: true })
  public soldDate: Date;

  @Field(() => String)
  @Property({ nullable: true })
  public type: string;

  ...
  ...
  ...

I don't have a One to One relationship to a Ticket in my Order entity. Tickets have an Order, but Orders don't necessarily have tickets. I didn't see one way relationships in the docs so I figured I would put that here just in case it has something to do with my issue.


Solution

  • My fields needed to be nullable in the order entity. It was a @nestjs/graphql related issue, not a mikro-orm related issue.

    export class Order extends BaseEntity {
      @Field(() => String, { nullable: true} )
      @Property({ nullable: true })
      public client: string;
    
      @Field(() => Date, { nullable: true} )
      @Property({ columnType: "date", nullable: true })
      public soldDate: Date;
    
      @Field(() => String, { nullable: true} )
      @Property({ nullable: true })
      public type: string;