Skip to content

Commit

Permalink
add programmtic typescript example with esm
Browse files Browse the repository at this point in the history
  • Loading branch information
PabloSzx committed Jun 25, 2021
1 parent 1036da0 commit 6cfdae8
Show file tree
Hide file tree
Showing 10 changed files with 722 additions and 34 deletions.
7 changes: 2 additions & 5 deletions .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,5 @@
"access": "restricted",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"ignore": [
"@graphql-codegen/testing",
"@graphql-codegen/website"
]
}
"ignore": ["@graphql-codegen/testing", "@graphql-codegen/website", "example-*"]
}
7 changes: 6 additions & 1 deletion bob.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
module.exports = {
ignore: ['@graphql-codegen/website', '@graphql-codegen/live-demo', '@graphql-codegen/config-schema'],
ignore: [
'@graphql-codegen/website',
'@graphql-codegen/live-demo',
'@graphql-codegen/config-schema',
'example-programmatic-typescript',
],
};
26 changes: 26 additions & 0 deletions examples/programmatic-typescript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "example-programmatic-typescript",
"version": "0.0.1",
"private": true,
"scripts": {
"dev:cjs": "tsup --watch src --onSuccess \"node dist/index.js\"",
"dev:mjs": "tsup --watch src --onSuccess \"node dist/index.mjs\""
},
"dependencies": {
"@graphql-codegen/core": "*",
"@graphql-codegen/typed-document-node": "^1.18.8",
"@graphql-codegen/typescript": "*",
"@graphql-codegen/typescript-operations": "^1.18.2",
"@graphql-codegen/typescript-resolvers": "^1.19.4",
"@graphql-ez/fastify": "^0.2.0",
"@graphql-tools/graphql-file-loader": "^6.2.7",
"@graphql-tools/load": "^6.2.8",
"fastify": "^3.18.0",
"graphql": "^15.5.1",
"prettier": "^2.3.1"
},
"devDependencies": {
"@types/node": "^15.12.4",
"tsup": "^4.11.2"
}
}
145 changes: 145 additions & 0 deletions examples/programmatic-typescript/src/ez.generated.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import type { GraphQLResolveInfo } from 'graphql';
import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
};

export type Query = {
__typename?: 'Query';
hello: Scalars['String'];
};

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

export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = {
fragment: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};

export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = {
selectionSet: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type StitchingResolver<TResult, TParent, TContext, TArgs> =
| LegacyStitchingResolver<TResult, TParent, TContext, TArgs>
| NewStitchingResolver<TResult, TParent, TContext, TArgs>;
export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| StitchingResolver<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
) => AsyncIterator<TResult> | Promise<AsyncIterator<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 between all available schema types and the resolvers types */
export type ResolversTypes = {
Query: ResolverTypeWrapper<{}>;
String: ResolverTypeWrapper<Scalars['String']>;
Boolean: ResolverTypeWrapper<Scalars['Boolean']>;
};

/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
Query: {};
String: Scalars['String'];
Boolean: Scalars['Boolean'];
};

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

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

/**
* @deprecated
* Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config.
*/
export type IResolvers<ContextType = any> = Resolvers<ContextType>;

export type HelloQueryVariables = Exact<{ [key: string]: never }>;

export type HelloQuery = { __typename?: 'Query' } & Pick<Query, 'hello'>;

export const HelloDocument = {
kind: 'Document',
definitions: [
{
kind: 'OperationDefinition',
operation: 'query',
name: { kind: 'Name', value: 'hello' },
selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'hello' } }] },
},
],
} as unknown as DocumentNode<HelloQuery, HelloQueryVariables>;
3 changes: 3 additions & 0 deletions examples/programmatic-typescript/src/graphql/hello.gql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
query hello {
hello
}
104 changes: 104 additions & 0 deletions examples/programmatic-typescript/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import Fastify from 'fastify';
import { promises } from 'fs';
import { parse, printSchema } from 'graphql';

import { codegen } from '@graphql-codegen/core';
import * as typedDocumentNode from '@graphql-codegen/typed-document-node';
import * as typescript from '@graphql-codegen/typescript';
import * as typescriptOperations from '@graphql-codegen/typescript-operations';
import * as typescriptResolvers from '@graphql-codegen/typescript-resolvers';
import { CreateApp, gql, EZContext } from '@graphql-ez/fastify';
import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';
import { loadDocuments } from '@graphql-tools/load';
import prettier from 'prettier';

import type { Resolvers } from './ez.generated';

declare module '@graphql-ez/fastify' {
interface EZResolvers extends Resolvers<EZContext> {}
}

const { writeFile } = promises;

const server = Fastify({
logger: true,
});

const ezApp = CreateApp({
schema: {
typeDefs: gql`
type Query {
hello: String!
}
`,
resolvers: {
Query: {
hello(_root, _args, _ctx) {
return 'world';
},
},
},
},
});

const { fastifyPlugin, getEnveloped } = ezApp.buildApp();

server.register(fastifyPlugin);

(async () => {
const { schema } = (await getEnveloped)();

const loadedDocuments = await loadDocuments(['src/graphql/**/*.gql'], {
loaders: [new GraphQLFileLoader()],
});

const config: typescript.TypeScriptPluginConfig &
typescriptResolvers.TypeScriptResolversPluginConfig &
typescriptOperations.TypeScriptDocumentsPluginConfig &
typedDocumentNode.TypeScriptTypedDocumentNodesConfig = {
useTypeImports: true,
};

const codegenCode = await codegen({
schema: parse(printSchema(schema)),
config,
documents: loadedDocuments,
filename: 'ez.generated.ts',
pluginMap: {
typescript,
typescriptResolvers,
typescriptOperations,
typedDocumentNode,
},
plugins: [
{
typescript: {},
},
{
typescriptResolvers: {},
},
{
typescriptOperations: {},
},
{
typedDocumentNode: {},
},
],
});

await writeFile(
'src/ez.generated.ts',
prettier.format(codegenCode, {
...(await prettier.resolveConfig(process.cwd())),
parser: 'typescript',
}),
{
encoding: 'utf-8',
}
);
})().catch(err => {
console.error(err);
process.exit(1);
});

server.listen(8080);
13 changes: 13 additions & 0 deletions examples/programmatic-typescript/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"rootDir": "../../"
},
"include": ["src/**/*.ts"]
}
6 changes: 6 additions & 0 deletions examples/programmatic-typescript/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const tsup: import('tsup').Options = {
target: 'es2019',
entryPoints: ['src/index.ts'],
format: ['cjs', 'esm'],
ignoreWatch: ['src/ez.generated.ts'],
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"packages/plugins/other/*",
"packages/presets/*",
"website",
"website/live-demo"
"website/live-demo",
"examples/*"
],
"nohoist": [
"@graphql-codegen/website/@docusaurus/*",
Expand Down
Loading

0 comments on commit 6cfdae8

Please sign in to comment.