Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[resolvers][federation] Fix mapper being incorrectly used as the base type for reference #10216

Open
wants to merge 8 commits into
base: federation-fixes
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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/thick-pianos-smoke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@graphql-codegen/visitor-plugin-common': patch
'@graphql-codegen/typescript-resolvers': patch
'@graphql-codegen/plugin-helpers': patch
---

Fix `mappers` usage with Federation

`mappers` was previously used as `__resolveReference`'s first param (usually called "reference"). However, this is incorrect because `reference` interface comes directly from `@key` and `@requires` directives. This patch fixes the issue by creating a new `FederationTypes` type and use it as the base for federation entity types when being used to type entity references
Original file line number Diff line number Diff line change
Expand Up @@ -1223,6 +1223,28 @@ export class BaseResolversVisitor<
).string;
}

public buildFederationTypes(): string {
const federationMeta = this._federation.getMeta();

if (Object.keys(federationMeta).length === 0) {
return '';
}

const declarationKind = 'type';
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(declarationKind)
.withName(this.convertName('FederationTypes'))
.withComment('Mapping of federation types')
.withBlock(
Object.keys(federationMeta)
.map(typeName => {
return indent(`${typeName}: ${this.convertName(typeName)}${this.getPunctuation(declarationKind)}`);
})
.join('\n')
).string;
}
Comment on lines +1226 to +1246
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This FederationTypes type will be used by federation entities to refer to the base types, similar to other types like ResolversParentTypes and ResolversTypes


public get schema(): GraphQLSchema {
return this._schema;
}
Expand Down Expand Up @@ -1498,6 +1520,7 @@ export class BaseResolversVisitor<
fieldNode: original,
parentType,
parentTypeSignature: this.getParentTypeForSignature(node),
federationTypeSignature: 'FederationType',
});
const mappedTypeKey = isSubscriptionType ? `${mappedType}, "${node.name}"` : mappedType;

Expand Down Expand Up @@ -1619,10 +1642,19 @@ export class BaseResolversVisitor<
);
}

const genericTypes: string[] = [
`ContextType = ${this.config.contextType.type}`,
this.transformParentGenericType(parentType),
];
if (this._federation.getMeta()[typeName]) {
const typeRef = `${this.convertName('FederationTypes')}['${typeName}']`;
genericTypes.push(`FederationType extends ${typeRef} = ${typeRef}`);
}

const block = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(declarationKind)
.withName(name, `<ContextType = ${this.config.contextType.type}, ${this.transformParentGenericType(parentType)}>`)
.withName(name, `<${genericTypes.join(', ')}>`)
.withBlock(fieldsContent.join('\n'));

this._collectedResolvers[node.name as any] = {
Expand Down
9 changes: 2 additions & 7 deletions packages/plugins/typescript/resolvers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,6 @@ export type ResolverWithResolve<TResult, TParent, TContext, TArgs> = {
const stitchingResolverUsage = `StitchingResolver<TResult, TParent, TContext, TArgs>`;

if (visitor.hasFederation()) {
if (visitor.config.wrapFieldDefinitions) {
defsToInclude.push(`export type UnwrappedObject<T> = {
[P in keyof T]: T[P] extends infer R | Promise<infer R> | (() => infer R2 | Promise<infer R2>)
? R & R2 : T[P]
};`);
Comment on lines -110 to -113
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

For a given type:

export type ProductMapper = {
  id: () => Promise<string>;
};

This type seems to return something like (() => Promise<string>) & string which is unusual - How can a function intersect with a string?

Regardless, since we move from ParentType to FederationType, I don't think this is needed in the future.

}

defsToInclude.push(
`export type ReferenceResolver<TResult, TReference, TContext> = (
reference: TReference,
Expand Down Expand Up @@ -244,6 +237,7 @@ export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs
) => TResult | Promise<TResult>;
`;

const federationTypes = visitor.buildFederationTypes();
const resolversTypeMapping = visitor.buildResolversTypes();
const resolversParentTypeMapping = visitor.buildResolversParentTypes();
const resolversUnionTypesMapping = visitor.buildResolversUnionTypes();
Expand Down Expand Up @@ -287,6 +281,7 @@ export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs
prepend,
content: [
header,
federationTypes,
resolversUnionTypesMapping,
resolversInterfaceTypesMapping,
resolversTypeMapping,
Expand Down
16 changes: 1 addition & 15 deletions packages/plugins/typescript/resolvers/src/visitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,7 @@ import {
ParsedResolversConfig,
} from '@graphql-codegen/visitor-plugin-common';
import autoBind from 'auto-bind';
import {
EnumTypeDefinitionNode,
FieldDefinitionNode,
GraphQLSchema,
ListTypeNode,
NamedTypeNode,
NonNullTypeNode,
} from 'graphql';
import { EnumTypeDefinitionNode, GraphQLSchema, ListTypeNode, NamedTypeNode, NonNullTypeNode } from 'graphql';
import { TypeScriptResolversPluginConfig } from './config.js';

export const ENUM_RESOLVERS_SIGNATURE =
Expand Down Expand Up @@ -96,13 +89,6 @@ export class TypeScriptResolversVisitor extends BaseResolversVisitor<
return `${this.config.immutableTypes ? 'ReadonlyArray' : 'Array'}<${str}>`;
}

protected getParentTypeForSignature(node: FieldDefinitionNode) {
if (this._federation.isResolveReferenceField(node) && this.config.wrapFieldDefinitions) {
return 'UnwrappedObject<ParentType>';
}
return 'ParentType';
}

NamedType(node: NamedTypeNode): string {
return `Maybe<${super.NamedType(node)}>`;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;


/** Mapping of union types */
export type ResolversUnionTypes<_RefType extends Record<string, unknown>> = ResolversObject<{
ChildUnion: ( Omit<Child, 'parent'> & { parent?: Maybe<_RefType['MyType']> } ) | ( MyOtherType );
Expand Down Expand Up @@ -425,6 +426,7 @@ export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;


/** Mapping of union types */
export type ResolversUnionTypes<_RefType extends Record<string, unknown>> = ResolversObject<{
ChildUnion: ( Omit<Types.Child, 'parent'> & { parent?: Types.Maybe<_RefType['MyType']> } ) | ( Types.MyOtherType );
Expand Down Expand Up @@ -770,6 +772,7 @@ export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs
info?: GraphQLResolveInfo
) => TResult | Promise<TResult>;


/** Mapping of union types */
export type ResolversUnionTypes<_RefType extends Record<string, unknown>> = ResolversObject<{
ChildUnion: ( Omit<Child, 'parent'> & { parent?: Maybe<_RefType['MyType']> } ) | ( MyOtherType );
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import '@graphql-codegen/testing';
import { codegen } from '@graphql-codegen/core';
import { parse } from 'graphql';
import { TypeScriptResolversPluginConfig } from '../src/config.js';
import { plugin } from '../src/index.js';

function generate({ schema, config }: { schema: string; config: TypeScriptResolversPluginConfig }) {
return codegen({
filename: 'graphql.ts',
schema: parse(schema),
documents: [],
plugins: [{ 'typescript-resolvers': {} }],
config,
pluginMap: { 'typescript-resolvers': { plugin } },
});
}

describe('TypeScript Resolvers Plugin + Apollo Federation - mappers', () => {
it('generates FederationTypes and use it for reference type', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
me: User
}

type User @key(fields: "id") {
id: ID!
name: String
}

type UserProfile {
id: ID!
user: User!
}
`;

const content = await generate({
schema: federatedSchema,
config: {
federation: true,
mappers: {
User: './mappers#UserMapper',
},
},
});

// User should have it
expect(content).toMatchInlineSnapshot(`
"import { GraphQLResolveInfo } from 'graphql';
import { UserMapper } from './mappers';
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;


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 = {}, TContext = {}, TArgs = {}> = 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 = {}, TContext = {}, TArgs = {}> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;

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

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

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

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

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



/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = {
Query: ResolverTypeWrapper<{}>;
User: ResolverTypeWrapper<UserMapper>;
ID: ResolverTypeWrapper<Scalars['ID']['output']>;
String: ResolverTypeWrapper<Scalars['String']['output']>;
UserProfile: ResolverTypeWrapper<Omit<UserProfile, 'user'> & { user: ResolversTypes['User'] }>;
Boolean: ResolverTypeWrapper<Scalars['Boolean']['output']>;
};

/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
Query: {};
User: UserMapper;
ID: Scalars['ID']['output'];
String: Scalars['String']['output'];
UserProfile: Omit<UserProfile, 'user'> & { user: ResolversParentTypes['User'] };
Boolean: Scalars['Boolean']['output'];
};

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

export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User'], FederationType extends FederationTypes['User'] = FederationTypes['User']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<FederationType, {"id":true}>, ContextType>;
id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
name?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};

export type UserProfileResolvers<ContextType = any, ParentType extends ResolversParentTypes['UserProfile'] = ResolversParentTypes['UserProfile']> = {
id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
user?: Resolver<ResolversTypes['User'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};

export type Resolvers<ContextType = any> = {
Query?: QueryResolvers<ContextType>;
User?: UserResolvers<ContextType>;
UserProfile?: UserProfileResolvers<ContextType>;
};

"
`);
});
});
Loading