#how to create field resolver of a Schema first union type?

1 messages · Page 1 of 1 (latest)

half nova
#

Hello
I have a union type
Type Vehicle = Car | Truck

Type Car {
licenseType: String!
}

Type Truck {
licenseType: String!
cargoSize: String!
}

I want to create a field resolver for the licenseType of Car and Truck
how do I do it ? didn't find alot of information online about it and would love to hear what to do

brisk plover
#

@half nova
To create a field resolver for the licenseType in both Car and Truck types in NestJS (assuming you're using GraphQL), you can follow this approach. Since both types (Car and Truck) have the licenseType field, you'll need to create a resolver for each type individually.

Here's how you can set up the resolvers for Car and Truck:

Define your types in GraphQL (SDL):
graphql

type Car {
  licenseType: String!
}

type Truck {
  licenseType: String!
  cargoSize: String!
}```

union Vehicle = Car | Truck
Create the resolvers for Car and Truck:
In NestJS, you can create a resolver class for each of these types and define a field resolver for licenseType.

typescript
```ts
import { Resolver, ResolveField, Parent } from '@nestjs/graphql';

@Resolver('Car')
export class CarResolver {
  @ResolveField(() => String)
  licenseType(@Parent() car) {
    // Implement logic to fetch or compute the licenseType for a car
    return car.licenseType;
  }
}

@Resolver('Truck')
export class TruckResolver {
  @ResolveField(() => String)
  licenseType(@Parent() truck) {
    // Implement logic to fetch or compute the licenseType for a truck
    return truck.licenseType;
  }
}```
half nova
#

can I resolve "Car" without the need for a fieldResolver for each field ? @brisk plover

half nova
#

can you please provide an example ?