Skip to content

Instantly share code, notes, and snippets.

@hos
Last active May 26, 2025 08:21
Show Gist options
  • Save hos/a4eccc23763766304102a18af22b7ba9 to your computer and use it in GitHub Desktop.
Save hos/a4eccc23763766304102a18af22b7ba9 to your computer and use it in GitHub Desktop.
Plugin for generating sdk for postgraphile schema direct usage.
import type { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
schema: '../../schema.graphql',
ignoreNoDocuments: true,
generates: {
'./server/src/gql/client/': {
documents: ['./server/src/gql/**/*.gql'],
preset: 'client',
plugins: ['./plugins/pgql.plugin.ts'],
presetConfig: {
withHooks: true,
persistedDocuments: true,
fragmentMasking: false,
},
},
},
};
export default config;

The MIT License (MIT) Copyright © 2025 Hovhannes Sanoyan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';
import { concatAST, OperationDefinitionNode, visit } from 'graphql';
export interface PgqlPluginConfig {
gqlImportPath?: string; // default 'src/lib/pgql.js'
documentsImportPath?: string; // default './graphql'
withTypes?: boolean; // default true
}
interface Operation {
name: string;
type: 'query' | 'mutation' | 'subscription';
documentName: string;
variablesType: string;
resultType: string;
}
class PgqlGenerator {
private operations: Operation[] = [];
private config: Required<PgqlPluginConfig>;
constructor(config: PgqlPluginConfig, documents: Types.DocumentFile[]) {
this.config = {
gqlImportPath: 'src/lib/pgql.js',
documentsImportPath: './graphql',
withTypes: true,
...config,
};
this.extractOperations(documents);
}
/* ---------- 1. Scan all GraphQL operations ---------- */
private extractOperations(documents: Types.DocumentFile[]): void {
const allAst = concatAST(documents.map((d) => d.document!));
visit(allAst, {
OperationDefinition: (node: OperationDefinitionNode) => {
if (!node.name) return;
const opSuffix =
node.operation === 'query'
? 'Query'
: node.operation === 'mutation'
? 'Mutation'
: 'Subscription';
const operationName = node.name.value;
const capitalizedName = operationName.charAt(0).toUpperCase() + operationName.slice(1);
const documentName = `${capitalizedName}Document`;
this.operations.push({
name: operationName,
type: node.operation,
documentName,
variablesType: `${capitalizedName}${opSuffix}Variables`,
resultType: `${capitalizedName}${opSuffix}`,
});
},
});
}
/* ---------- 2. Generate imports ---------- */
private getImports(): string {
const imports: string[] = [];
imports.push(
`import { gqlQueryAs, GqlRequestIdentifier, GqlQueryAsOptions } from '${this.config.gqlImportPath}';`,
`import { ExecutionResult } from 'postgraphile/graphql';`
);
return imports.join('\n');
}
/* ---------- 3. One property per operation ---------- */
private buildSdkMethod(op: Operation): string {
const { name, documentName, variablesType, resultType } = op;
const methodName = name;
// Does this op actually accept variables?
const needsVars = !['{}', 'Exact<{}>', variablesType.replace(/Variables$/, '')].includes(
variablesType
);
const paramsWithVars = `(
requestContext: GqlRequestIdentifier,
variables: ${variablesType},
operationName?: string,
options?: GqlQueryAsOptions
): Promise<ExecutionResult<${resultType}>>`;
const paramsWithoutVars = `(
requestContext: GqlRequestIdentifier,
operationName?: string,
options?: GqlQueryAsOptions
): Promise<ExecutionResult<${resultType}>>`;
const params = needsVars ? paramsWithVars : paramsWithoutVars;
const varsArg = needsVars ? 'variables' : 'undefined';
return `${methodName}: async ${params} => {
return gqlQueryAs(
requestContext,
${documentName},
${varsArg},
operationName || '${name}',
options
);
}`;
}
/* ---------- 4. Collect everything into sdk ---------- */
private generateSdkObject(): string {
if (!this.operations.length) return '// No GraphQL operations found';
const methods = this.operations.map((o) => this.buildSdkMethod(o)).join(',\n\n');
return `export const sdk = {
${methods}
} as const;
export type GqlSdk = typeof sdk;`;
}
/* ---------- 5. Public entry ---------- */
public generate(): string {
return [
'// Generated GraphQL SDK (auto-generated – do not edit)',
'',
this.getImports(),
'',
this.generateSdkObject(),
].join('\n');
}
}
/* ---------- Plugin entry-point ---------- */
export const plugin: PluginFunction<PgqlPluginConfig> = (_schema, documents, config = {}) => {
const generator = new PgqlGenerator(config, documents);
return generator.generate();
};
export type GqlQueryAsOptions = {
};
export async function gqlQueryAs<TData = any, TVariables = any>(
_requestContext: Grafast.RequestContext,
document: DocumentNode | TypedDocumentNode<TData, TVariables>,
variableValues?: TVariables | null,
operationName?: string,
options?: GqlQueryAsOptions
): Promise<ExecutionResult<TData, any>> {
let requestContext: Partial<Grafast.RequestContext> | null = null;
// Validate the GraphQL document against the schema:
const errors = validate(schema, document);
if (errors.length > 0) {
throw new Error(`Validation error(s) occurred`, { cause: errors });
}
// Execute the request using Grafast:
const args = await hookArgs({
schema,
document,
variableValues,
operationName,
resolvedPreset,
requestContext,
});
const result = (await execute(args)) as ExecutionResult<TData, TVariables>;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment