Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/federation-external-fields-to-pick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@eddeee888/gcg-typescript-resolver-files': patch
---

Fix Federation `@external` fields being picked in object type resolvers when `extend type` is used across multiple modules

Previously, every field of an object type was added to each module's `Pick<...>`, including `@external` fields that `typescript-resolvers` does not generate resolver types for. With `useIndexSignature: true`, this made the external fields required in the resolver object; without it, the `Pick` keys did not exist on the resolvers type. Both resulted in type errors.

Fields to pick are now filtered using the same `ApolloFederation` logic as `typescript-resolvers` when `typesPluginsConfig.federation` is enabled i.e. `@external` fields (or fields of an `@external` object type) are skipped, unless there is a `@provides` path to them.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ const config: CodegenConfig = {
},
{ schema: `${baseDir}/subgraph-users/**/schema.graphqls` }
),

[`${baseDir}/subgraph-shipping`]: defineConfig(
{
typeDefsFilePath: false,
mergeSchema: false,
typesPluginsConfig: { federation: true },
},
{ schema: `${baseDir}/subgraph-shipping/**/schema.graphqls` }
),
},
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { ProductResolvers } from './../../types.generated';
export const Product: Pick<ProductResolvers, 'shippingEstimate'|'upc'|'__resolveReference'> = {
/* Implement Product resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

import type { QueryResolvers } from './../../../types.generated';
export const cheapestProduct: NonNullable<QueryResolvers['cheapestProduct']> = async (_parent, _arg, _ctx) => { /* Implement Query.cheapestProduct resolver logic here */ };
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
type Query {
cheapestProduct: Product @provides(fields: "name")
}

type Product @key(fields: "upc") {
upc: String!
weight: Int @external
shippingEstimate: Int @requires(fields: "weight")
}

extend schema
@link(
url: "https://specs.apollo.dev/federation/v2.3"
import: ["@key", "@external", "@requires", "@provides"]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { ProductResolvers } from './../../types.generated';
export const Product: Pick<ProductResolvers, 'name'|'tax'|'__resolveReference'> = {
/* Implement Product resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
extend type Product @key(fields: "upc") {
name: String @external
price: Int @external
tax: Int @requires(fields: "price")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* This file was automatically generated. DO NOT UPDATE MANUALLY. */
import type { Resolvers } from './types.generated';
import { cheapestProduct as Query_cheapestProduct } from './part-1/resolvers/Query/cheapestProduct';
import { Product as part_2_Product } from './part-2/resolvers/Product';
import { Product as part_1_Product } from './part-1/resolvers/Product';
export const resolvers: Resolvers = {
Query: { cheapestProduct: Query_cheapestProduct },


Product: { ...part_2_Product,...part_1_Product }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { GraphQLResolveInfo } from 'graphql';
export type Maybe<T> = T | null | undefined;
export type InputMaybe<T> = T | null | undefined;
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: { input: string; output: string; }
String: { input: string; output: string; }
Boolean: { input: boolean; output: boolean; }
Int: { input: number; output: number; }
Float: { input: number; output: number; }
_FieldSet: { input: unknown; output: unknown; }
};

export type Product = {
__typename?: 'Product';
name?: Maybe<Scalars['String']['output']>;
price?: Maybe<Scalars['Int']['output']>;
shippingEstimate?: Maybe<Scalars['Int']['output']>;
tax?: Maybe<Scalars['Int']['output']>;
upc: Scalars['String']['output'];
weight?: Maybe<Scalars['Int']['output']>;
};

export type Query = {
__typename?: 'Query';
cheapestProduct?: Maybe<Product>;
};



export type ResolverTypeWrapper<T> = Promise<T> | T;

export type ReferenceResolver<TResult, TReference, TContext> = (
reference: TReference,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;

type ScalarCheck<T, S> = S extends true ? T : NullableCheck<T, S>;
type NullableCheck<T, S> = Maybe<T> extends T ? Maybe<ListCheck<NonNullable<T>, S>> : ListCheck<T, S>;
type ListCheck<T, S> = T extends (infer U)[] ? NullableCheck<U, S>[] : GraphQLRecursivePick<T, S>;
export type GraphQLRecursivePick<T, S> = { [K in keyof T & keyof S]: ScalarCheck<T[K], S[K]> };


export type ResolverWithResolve<TResult, TParent, TContext, TArgs> = {
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type Resolver<TResult, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> = ResolverFn<TResult, TParent, TContext, TArgs> | ResolverWithResolve<TResult, TParent, TContext, TArgs>;

export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;

export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>;

export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;

export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
}

export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}

export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;

export type SubscriptionResolver<TResult, TKey extends string, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;

export type TypeResolveFn<TTypes, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes> | Promise<Maybe<TTypes>>;

export type IsTypeOfResolverFn<T = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean>;

export type NextResolverFn<T> = () => Promise<T>;

export type DirectiveResolverFn<TResult = Record<PropertyKey, never>, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;

/** Mapping of federation types */
export type FederationTypes = {
Product: Product;
};

/** Mapping of federation reference types */
export type FederationReferenceTypes = {
Product:
( { __typename: 'Product' }
& GraphQLRecursivePick<FederationTypes['Product'], {"upc":true}>
& ( Record<PropertyKey, never>
| GraphQLRecursivePick<FederationTypes['Product'], {"weight":true}>
| GraphQLRecursivePick<FederationTypes['Product'], {"weight":true,"price":true}>
| GraphQLRecursivePick<FederationTypes['Product'], {"price":true}> ) );
};



/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = {
Product: ResolverTypeWrapper<Product>;
String: ResolverTypeWrapper<Scalars['String']['output']>;
Int: ResolverTypeWrapper<Scalars['Int']['output']>;
Query: ResolverTypeWrapper<Record<PropertyKey, never>>;
Boolean: ResolverTypeWrapper<Scalars['Boolean']['output']>;
};

/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
Product: Product | FederationReferenceTypes['Product'];
String: Scalars['String']['output'];
Int: Scalars['Int']['output'];
Query: Record<PropertyKey, never>;
Boolean: Scalars['Boolean']['output'];
};

export type ProductResolvers<ContextType = any, ParentType extends ResolversParentTypes['Product'] = ResolversParentTypes['Product'], FederationReferenceType extends FederationReferenceTypes['Product'] = FederationReferenceTypes['Product']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['Product']> | FederationReferenceType, FederationReferenceType, ContextType>;
name?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
shippingEstimate?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
tax?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
upc?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
};

export type QueryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = {
cheapestProduct?: Resolver<Maybe<ResolversTypes['Product']>, ParentType, ContextType>;
};

export type Resolvers<ContextType = any> = {
Product?: ProductResolvers<ContextType>;
Query?: QueryResolvers<ContextType>;
};

Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { buildSchema, type GraphQLObjectType } from 'graphql';
import { ApolloFederation } from '@graphql-codegen/plugin-helpers';
import { findFieldNamesToGenerate } from './findFieldNamesToGenerate.js';

const schema = buildSchema(/* GraphQL */ `
directive @key(fields: String!) repeatable on OBJECT
directive @external on FIELD_DEFINITION | OBJECT
directive @requires(fields: String!) on FIELD_DEFINITION
directive @provides(fields: String!) on FIELD_DEFINITION

type Query {
product: Product @provides(fields: "name")
warehouse: Warehouse @provides(fields: "address")
}

type Product @key(fields: "id") {
id: ID!
}

extend type Product {
name: String @external
weight: Int @external
shippingEstimate: Int @requires(fields: "weight")
}

type Warehouse @key(fields: "id") {
id: ID!
}

extend type Warehouse @external {
address: String
capacity: Int
}
`);

const getFieldNames = (federation: boolean, typeName: string): string[] => [
...findFieldNamesToGenerate({
namedType: schema.getType(typeName) as GraphQLObjectType,
apolloFederation: new ApolloFederation({
enabled: federation,
schema,
meta: {},
}),
}),
];

describe('findFieldNamesToGenerate', () => {
it('returns all fields if federation is disabled', () => {
expect(getFieldNames(false, 'Product')).toEqual([
'id',
'name',
'weight',
'shippingEstimate',
]);
});

it('skips `@external` fields without `@provides` path if federation is enabled', () => {
expect(getFieldNames(true, 'Product')).toEqual([
'id',
'name',
'shippingEstimate',
]);
});

it('returns only fields with `@provides` path if object type extension is `@external`', () => {
expect(getFieldNames(true, 'Warehouse')).toEqual(['address']);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type {
FieldDefinitionNode,
GraphQLObjectType,
ObjectTypeDefinitionNode,
} from 'graphql';
import type { ApolloFederation } from '@graphql-codegen/plugin-helpers';

/**
* findFieldNamesToGenerate
*
* Finds the names of an object type's fields that `typescript-resolvers` generates resolver types for,
* using the same `ApolloFederation` logic as `typescript-resolvers` so the two never disagree.
* e.g. In Federation, `@external` fields (or fields of an `@external` object type) are skipped unless there is a `@provides` path to them.
*/
export const findFieldNamesToGenerate = ({
namedType,
apolloFederation,
}: {
namedType: GraphQLObjectType;
apolloFederation: ApolloFederation;
}): Set<string> => {
// `findFieldNodesToGenerate` is called by `typescript-resolvers` with visitor-transformed nodes,
// where each field is wrapped as `{ node: FieldDefinitionNode }`. We mimic that shape here.
// Directives are gathered from the definition and every extension, so `@external` on any of them is detected.
const node = {
name: { value: namedType.name },
directives: [namedType.astNode, ...namedType.extensionASTNodes].flatMap(
(typeNode) => typeNode?.directives || []
),
fields: Object.values(namedType.getFields()).map((field) => ({
node: field.astNode || { name: { value: field.name } },
})),
} as unknown as ObjectTypeDefinitionNode;
Comment on lines +25 to +33

@eddeee888 eddeee888 Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @BuddhaBing, this bit is going to be hard to maintain because:

  • it's rebuilding the expected node that apolloFederation needs, with transformed values i.e. it's leaking ApolloFederation's logic here
  • findFieldNodesToGenerate already ran in the main resolver-types i.e. this'd be doubling up the work

Currently, we are passing the typescript-resolvers run meta via meta which may look like this:

userDefined: {
      Product: {
        name: 'ProductResolvers',
        hasIsTypeOf: false,
        federation: { hasResolveReference: true }
      },
      Query: { name: 'QueryResolvers', hasIsTypeOf: false }
    }

Here's how I think we could tackle this problem hollistically:

  1. add some more metadata about which fields are available into this block
  2. then use said metadata (accessible by ctx.config.generatedTypesFileMeta) to filter out the fieldsToPick i.e. fieldsToPick contains all fields of a module, if it wasn't generated in the metadata, do not show it)

Let me know what you think 🙂
This'd be a bit longer but it keeps the existing principles. I could help create PRs in either repo to move things along if you'd like. Let me know


return new Set(
apolloFederation
.findFieldNodesToGenerate({ node })
.map((fieldNode: FieldDefinitionNode) => fieldNode.name.value)
);
};
Loading