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

Use typescript resolvers meta to support namingConvention for generated types of GraphQL definitions #301

Merged
merged 7 commits into from
Jun 13, 2024
Merged
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
5 changes: 5 additions & 0 deletions .changeset/hot-spoons-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@eddeee888/gcg-typescript-resolver-files': minor
---

Use reported generated type names from @graphql-codegen/typescript-resolvers meta to support all naming convention
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const config: CodegenConfig = {
resolverRelativeTargetDir: 'rslvrs',
resolverMainFile: 'resolvers.gen.ts',
typeDefsFilePath: false,
resolverGeneration: 'all',
scalarsOverrides: {
BigInt: {
resolver:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { CURRENCYRESOLVERS } from './../../types.gen';
export const Currency: CURRENCYRESOLVERS = {
USD: 'USD',
AUD: 'AUD',
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { ERRORRESOLVERS } from './../../types.gen';
export const Error: ERRORRESOLVERS = {
/* Implement Error interface logic here */
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { ERRORTYPERESOLVERS } from './../../types.gen';
export const ErrorType: ERRORTYPERESOLVERS = {
NOT_FOUND: 'NOT_FOUND',
INPUT_VALIDATION_ERROR: 'INPUT_VALIDATION_ERROR',
FORBIDDEN_ERROR: 'FORBIDDEN_ERROR',
UNEXPECTED_ERROR: 'UNEXPECTED_ERROR',
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { PaginationResultResolvers } from './../../types.gen';
export const PaginationResult: PaginationResultResolvers = {
import type { PAGINATIONRESULTRESOLVERS } from './../../types.gen';
export const PaginationResult: PAGINATIONRESULTRESOLVERS = {
/* Implement PaginationResult resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { StandardErrorResolvers } from './../../types.gen';
export const StandardError: StandardErrorResolvers = {
import type { STANDARDERRORRESOLVERS } from './../../types.gen';
export const StandardError: STANDARDERRORRESOLVERS = {
/* Implement StandardError resolver logic here */
};
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ import { User } from './user/rslvrs/User';
import { UserResult } from './user/rslvrs/UserResult';
import { SomeOtherScalars } from './base/rslvrs/SomeOtherScalars';
import { WithInputOutput } from './base/rslvrs/WithInputOutput';
import { Error } from './base/rslvrs/Error';
import { TopicByIdPayload } from './topic/rslvrs/TopicByIdPayload';
import { TopicCreatePayload } from './topic/rslvrs/TopicCreatePayload';
import { TopicEditPayload } from './topic/rslvrs/TopicEditPayload';
import { TopicsCreatedByUserPayload } from './topic/rslvrs/TopicsCreatedByUserPayload';
import { UserPayload } from './user/rslvrs/UserPayload';
import { Currency } from './base/rslvrs/Currency';
import { ErrorType } from './base/rslvrs/ErrorType';
import CustomBigIntResolver from './base/CustomBigIntResolver';
import { DateTimeResolver } from 'graphql-scalars';
export const resolvers: Resolvers = {
Expand All @@ -45,6 +53,14 @@ export const resolvers: Resolvers = {
UserResult: UserResult,
SomeOtherScalars: SomeOtherScalars,
WithInputOutput: WithInputOutput,
Error: Error,
TopicByIdPayload: TopicByIdPayload,
TopicCreatePayload: TopicCreatePayload,
TopicEditPayload: TopicEditPayload,
TopicsCreatedByUserPayload: TopicsCreatedByUserPayload,
UserPayload: UserPayload,
Currency: Currency,
ErrorType: ErrorType,
BigInt: CustomBigIntResolver,
DateTime: DateTimeResolver,
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { MutationResolvers } from './../../../types.gen';
import type { MUTATIONRESOLVERS } from './../../../types.gen';
export const topicCreate: NonNullable<
MutationResolvers['topicCreate']
MUTATIONRESOLVERS['topicCreate']
> = async (_parent, _arg, _ctx) => {
/* Implement Mutation.topicCreate resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { MutationResolvers } from './../../../types.gen';
export const topicEdit: NonNullable<MutationResolvers['topicEdit']> = async (
import type { MUTATIONRESOLVERS } from './../../../types.gen';
export const topicEdit: NonNullable<MUTATIONRESOLVERS['topicEdit']> = async (
_parent,
_arg,
_ctx
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { QueryResolvers } from './../../../types.gen';
export const topicById: NonNullable<QueryResolvers['topicById']> = async (
import type { QUERYRESOLVERS } from './../../../types.gen';
export const topicById: NonNullable<QUERYRESOLVERS['topicById']> = async (
_parent,
_arg,
_ctx
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { QueryResolvers } from './../../../types.gen';
import type { QUERYRESOLVERS } from './../../../types.gen';
export const topicsCreatedByUser: NonNullable<
QueryResolvers['topicsCreatedByUser']
QUERYRESOLVERS['topicsCreatedByUser']
> = async (_parent, _arg, _ctx) => {
/* Implement Query.topicsCreatedByUser resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TopicResolvers } from './../../types.gen';
export const Topic: TopicResolvers = {
import type { TOPICRESOLVERS } from './../../types.gen';
export const Topic: TOPICRESOLVERS = {
/* Implement Topic resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { TOPICBYIDPAYLOADRESOLVERS } from './../../types.gen';
export const TopicByIdPayload: TOPICBYIDPAYLOADRESOLVERS = {
/* Implement TopicByIdPayload union logic here */
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TopicByIdResultResolvers } from './../../types.gen';
export const TopicByIdResult: TopicByIdResultResolvers = {
import type { TOPICBYIDRESULTRESOLVERS } from './../../types.gen';
export const TopicByIdResult: TOPICBYIDRESULTRESOLVERS = {
/* Implement TopicByIdResult resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { TOPICCREATEPAYLOADRESOLVERS } from './../../types.gen';
export const TopicCreatePayload: TOPICCREATEPAYLOADRESOLVERS = {
/* Implement TopicCreatePayload union logic here */
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TopicCreateResultResolvers } from './../../types.gen';
export const TopicCreateResult: TopicCreateResultResolvers = {
import type { TOPICCREATERESULTRESOLVERS } from './../../types.gen';
export const TopicCreateResult: TOPICCREATERESULTRESOLVERS = {
/* Implement TopicCreateResult resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { TOPICEDITPAYLOADRESOLVERS } from './../../types.gen';
export const TopicEditPayload: TOPICEDITPAYLOADRESOLVERS = {
/* Implement TopicEditPayload union logic here */
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TopicEditResultResolvers } from './../../types.gen';
export const TopicEditResult: TopicEditResultResolvers = {
import type { TOPICEDITRESULTRESOLVERS } from './../../types.gen';
export const TopicEditResult: TOPICEDITRESULTRESOLVERS = {
/* Implement TopicEditResult resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { TOPICSCREATEDBYUSERPAYLOADRESOLVERS } from './../../types.gen';
export const TopicsCreatedByUserPayload: TOPICSCREATEDBYUSERPAYLOADRESOLVERS = {
/* Implement TopicsCreatedByUserPayload union logic here */
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TopicsCreatedByUserResultResolvers } from './../../types.gen';
export const TopicsCreatedByUserResult: TopicsCreatedByUserResultResolvers = {
import type { TOPICSCREATEDBYUSERRESULTRESOLVERS } from './../../types.gen';
export const TopicsCreatedByUserResult: TOPICSCREATEDBYUSERRESULTRESOLVERS = {
/* Implement TopicsCreatedByUserResult resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ProfileResolvers } from './../../types.gen';
export const Profile: ProfileResolvers = {
import type { PROFILERESOLVERS } from './../../types.gen';
export const Profile: PROFILERESOLVERS = {
/* Implement Profile resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { QueryResolvers } from './../../../types.gen';
export const me: NonNullable<QueryResolvers['me']> = async (
import type { QUERYRESOLVERS } from './../../../types.gen';
export const me: NonNullable<QUERYRESOLVERS['me']> = async (
_parent,
_arg,
_ctx
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { QueryResolvers } from './../../../types.gen';
import type { QUERYRESOLVERS } from './../../../types.gen';
export const userByAccountName: NonNullable<
QueryResolvers['userByAccountName']
QUERYRESOLVERS['userByAccountName']
> = async (_parent, _arg, _ctx) => {
/* Implement Query.userByAccountName resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { SubscriptionResolvers } from './../../../types.gen';
import type { SUBSCRIPTIONRESOLVERS } from './../../../types.gen';
export const profileChanges: NonNullable<
SubscriptionResolvers['profileChanges']
SUBSCRIPTIONRESOLVERS['profileChanges']
> = {
subscribe: async (_parent, _arg, _ctx) => {
/* Implement Subscription.profileChanges resolver logic here */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { UserResolvers } from './../../types.gen';
export const User: UserResolvers = {
import type { USERRESOLVERS } from './../../types.gen';
export const User: USERRESOLVERS = {
/* Implement User resolver logic here */
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { USERPAYLOADRESOLVERS } from './../../types.gen';
export const UserPayload: USERPAYLOADRESOLVERS = {
/* Implement UserPayload union logic here */
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { UserResultResolvers } from './../../types.gen';
export const UserResult: UserResultResolvers = {
import type { USERRESULTRESOLVERS } from './../../types.gen';
export const UserResult: USERRESULTRESOLVERS = {
/* Implement UserResult resolver logic here */
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as typeScriptResolversPlugin from '@graphql-codegen/typescript-resolver
import type { GraphQLSchema } from 'graphql';
import type { SourceFile, Project } from 'ts-morph';
import type { ServerConfig } from '@eddeee888/gcg-server-config';
import type { GeneratedTypesFileMeta } from '../generateResolverFiles';

export const addVirtualTypesFileToTsMorphProject = async ({
tsMorphProject,
Expand All @@ -19,7 +20,10 @@ export const addVirtualTypesFileToTsMorphProject = async ({
resolverTypesPath: string;
resolverTypesConfig: ServerConfig;
addConfig?: AddPluginConfig;
}): Promise<SourceFile> => {
}): Promise<{
typesSourceFile: SourceFile;
meta: GeneratedTypesFileMeta;
}> => {
const typesFile = await generateVirtualTypesFile({
schemaAst,
resolverTypesPath,
Expand All @@ -33,7 +37,7 @@ export const addVirtualTypesFileToTsMorphProject = async ({
{ overwrite: true }
);

return typesSourceFile;
return { typesSourceFile, meta: typesFile.meta };
};

/**
Expand All @@ -53,6 +57,7 @@ const generateVirtualTypesFile = async ({
}): Promise<{
filePath: string;
content: string;
meta: GeneratedTypesFileMeta;
}> => {
const [typescriptResult, typescriptResolversResult, addResult] =
await Promise.all([
Expand All @@ -75,6 +80,10 @@ const generateVirtualTypesFile = async ({
${addResultAsComplextOutput.content}
${addResultAsComplextOutput.append?.join('\n')}
`,
meta: {
generatedResolverTypes:
typescriptResolversResult.meta?.generatedResolverTypes || {},
},
};
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export const addResolverMainFiles = ({
}, resolverMainFiles);

const resolversIdentifier = 'resolvers';
const resolversTypeName = 'Resolvers'; // Generated type from typescript-resolvers plugin
const resolversTypeName = 'Resolvers'; // FIXME: use data from `typescript-resolvers`'s `meta`

Object.entries(resolverMainFiles).forEach(([resolverMainFilename, file]) => {
const outputDir = path.dirname(resolverMainFilename);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import type { SourceFile, Project } from 'ts-morph';
import type * as typeScriptResolversPlugin from '@graphql-codegen/typescript-resolvers';
import type { GraphQLObjectTypeResolversToGenerate } from '../getGraphQLObjectTypeResolversToGenerate';
import type { TypeMappersMap } from '../parseTypeMappers';
import type { ImportLineMeta, RootObjectType } from '../utils';
import type { ParsedPresetConfig } from '../validatePresetConfig';
import type { NormalizedResolverName } from '../parseGraphQLSchema';
import type { ParsedGraphQLSchemaMeta } from '../parseGraphQLSchema';

export type GeneratedTypesFileMeta = {
generatedResolverTypes: NonNullable<
Awaited<ReturnType<typeof typeScriptResolversPlugin.plugin>>['meta']
>['generatedResolverTypes'];
};

interface BaseVirtualFile {
__filetype: string;
content: string;
Expand Down Expand Up @@ -136,6 +143,7 @@ export interface GenerateResolverFilesContext {
graphQLObjectTypeResolversToGenerate: GraphQLObjectTypeResolversToGenerate;
fixObjectTypeResolvers: ParsedPresetConfig['fixObjectTypeResolvers'];
emitLegacyCommonJSImports: boolean;
generatedTypesFileMeta: GeneratedTypesFileMeta;
};
result: {
files: Record<string, StandardFile | ResolverFile>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ export const visitNamedType = <T = null>(
resolversTypeMeta: {
module: relativePathToResolverTypesFile,
moduleType: 'file',
typeNamedImport,
typeString,
typeNamedImport: typeNamedImport(ctx.config.generatedTypesFileMeta),
typeString: typeString(ctx.config.generatedTypesFileMeta),
},
},
ctx
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
} from '../utils';
import { parseLocationForOutputDir } from './parseLocationForOutputDir';
import { normalizeResolverName } from './normalizeResolverName';
import type { GeneratedTypesFileMeta } from '../generateResolverFiles';

interface ParseGraphQLSchemaParams {
schemaAst: GraphQLSchema;
Expand All @@ -54,8 +55,8 @@ export interface ResolverDetails {
};
relativePathFromBaseToModule: string[];
normalizedResolverName: ReturnType<typeof normalizeResolverName>;
typeNamedImport: string;
typeString: string;
typeNamedImport: (generatedTypesFileMeta: GeneratedTypesFileMeta) => string;
typeString: (generatedTypesFileMeta: GeneratedTypesFileMeta) => string;
relativePathToResolverTypesFile: string;
}

Expand Down Expand Up @@ -517,10 +518,18 @@ const createResolverDetails = ({
},
relativePathFromBaseToModule,
normalizedResolverName,
typeNamedImport: `${schemaType}Resolvers`, // TODO: use from `typescript-resolvers`'s `meta`
typeString: belongsToRootObject
? `${schemaType}Resolvers['${resolverName}']`
: `${schemaType}Resolvers`, // TODO: use from `typescript-resolvers`'s `meta`
typeNamedImport: ({ generatedResolverTypes }) =>
generatedResolverTypes[schemaType]?.name || `${schemaType}Resolvers`,
typeString: ({ generatedResolverTypes }) => {
if (belongsToRootObject) {
return generatedResolverTypes[schemaType]
? `${generatedResolverTypes[schemaType].name}['${resolverName}']`
: `${schemaType}Resolvers['${resolverName}']`;
}
return (
generatedResolverTypes[schemaType]?.name || `${schemaType}Resolvers`
);
},
relativePathToResolverTypesFile: relativeModulePath(
resolversOutputDir,
resolverTypesPath
Expand Down
24 changes: 13 additions & 11 deletions packages/typescript-resolver-files/src/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,17 +144,18 @@ export const preset: Types.OutputPreset<RawPresetConfig> = {
// typesSourceFile is the virtual `types.generated.ts`
// This is useful when we need to do static analysis as most types come from this file
// e.g. comparing mappers field type vs schema object field type
const typesSourceFile = await profiler.run(
() =>
addVirtualTypesFileToTsMorphProject({
tsMorphProject,
schemaAst,
resolverTypesConfig,
resolverTypesPath,
addConfig: normalizedAdd?.[resolverTypesPath],
}),
createProfilerRunName('addVirtualTypesFileToTsMorphProject')
);
const { typesSourceFile, meta: generatedTypesFileMeta } =
await profiler.run(
() =>
addVirtualTypesFileToTsMorphProject({
tsMorphProject,
schemaAst,
resolverTypesConfig,
resolverTypesPath,
addConfig: normalizedAdd?.[resolverTypesPath],
}),
createProfilerRunName('addVirtualTypesFileToTsMorphProject')
);

const graphQLObjectTypeResolversToGenerate = await profiler.run(
async () =>
Expand Down Expand Up @@ -244,6 +245,7 @@ export const preset: Types.OutputPreset<RawPresetConfig> = {
...mergedConfig.externalResolvers,
},
emitLegacyCommonJSImports,
generatedTypesFileMeta,
},
result,
}),
Expand Down
Loading
Loading