dangcuuson / graphql-schema-typescript

Generate TypeScript from GraphQL's schema type definitions
190 stars 36 forks source link

Resolving Union Types #16

Closed janhartmann closed 5 years ago

janhartmann commented 5 years ago

First of all, thank you for this awesome library! It has been so much easier to get up and running with TypeScript and GraphQL.

I have in a situation, where I need to resolve a union type property in my schema:

type UnitEvent {
  id: String!
  details: UnitEventDetails
}

union UnitEventDetails = DamageReportEvent | CanErrorEvent

type DamageReportEvent {
  damageReportId: String
}

type CanErrorEvent {
  canErrorId: String
}

In my 'UnitEventResolver` I have the following:

const unitEventResolver: GQLUnitEventTypeResolver<IUnitEventApiResponse> = {
  id: parent => {
    return parent.eventId;
  },
  details: parent => {
    return parent;
  }
};

export default unitEventResolver;

Then in my UnitEventDetailsResolver I have:

const unitEventDetailsResolver: GQLUnitEventDetailsTypeResolver = (
  parent: IUnitEventApiResponse
) => {
  switch (parent.type) {
    case 1:
      return "DamageReportEvent";
    case 7:
      return "CanErrorEvent";
  }
};

export default unitEventDetailsResolver;

And finally in my CanErrorEventResolver:

const canErrorEventResolver: GQLCanErrorEventTypeResolver<
  IUnitEventApiResponse
> = {
  canErrorId: parent => {
    return parent.data.canErrorId;
  }
};

export default canErrorEventResolver;

However, I am getting this message:

"message": "Abstract type UnitEventDetails must resolve to an Object type at runtime for field UnitEvent.details with value { [REDACTED], type: 7, [REDACTED] }, received \"undefined\". Either the UnitEventDetails type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."

I am also getting this in the console:

Type "UnitEventDetails" is missing a "__resolveType" resolver. Pass false into "resolverValidationOptions.requireResolversForResolveType" to disable this warning.

I have tried messing around with the types, but unable to make it work?

Can you point me in a direction to solve this?

Thanks!

janhartmann commented 5 years ago

Aaah, after looking through the generated types, I had to do this in my export:

UnitEventDetails: {
    __resolveType: UnitEventDetailsResolver
  },