graphql-codegen-typed-query
v0.1.1
Published
GraphQL Code Generator plugin that makes your GraphQL queries be type-safe
Downloads
1
Readme
graphql-codegen-typed-query
yarn add graphql-codegen-typed-query
Simple GraphQL Code Generator
plugin that makes your GraphQL queries be type-safe.
How to use
You need to install following packages first.
graphql
@types/graphql
@graphql-codegen/cli
@graphql-codegen/typescript
@graphql-codegen/typescript-operations
Prepare your own schema GraphQL file.
./schema.graphql
type User {
id: ID!
nickname: String!
}
type Query {
users: [User!]!
}
Now prepare your queries.
./queries/users.graphql
query Users {
users {
id
nickname
}
}
Create codegen.yml
at the project root.
./codegen.yml
schema: "schema.graphql"
documents: "queries/**/*.graphql"
generates:
./generated/schema.ts:
- "typescript"
- "typescript-operations"
- "node_modules/graphql-codegen-typed-query/dist/plugin.js"
Now generate!
yarn graphql-codegen
You'll see ./generated/schema.ts
file generated. It will contain objects with raw query document & type information packed together.
// ./generated/schema.ts
/*
Some types genereated by typescript & typescript-operations plugin here...
*/
/* Types generated by typescript-operations */
export type UsersQueryVariables = {};
export type UsersQuery = { __typename?: "Query" } & {
users: Array<{ __typename?: "User" } & Pick<User, "id" | "nickname">>;
};
/* Types generated by graphql-codegen-typed-query */
export interface TypedQuery<Result> {
rawDocument: string;
_result?: Result;
}
export const UsersQuery: TypedQuery<UsersQuery> = {
rawDocument: `query Users {
users {
id
nickname
}
}
`
};
Now everything's ready!
Tips
Define your own executeTypedQuery
function.
// ./typed-query.ts
import { graphql, ExecutionResult } from "graphql";
import { TypedQuery } from "./generated/schema";
import { schema } from "./path/to/my-executable-schema";
export async function executeTypedQuery<Result>(
query: TypedQuery<Result>
): Promise<ExecutionResult<Result>> {
return graphql(schema, query.rawDocument);
}
Import your query & enjoy type-safety!
// ./main.ts
import { executeTypedQuery } from "./typed-query";
import { UsersQuery } from "./generated/schema";
async function main() {
// `result` inferred to have type `ExecutionResult<UsersQuery>`! Yay!
const result = await executeTypedQuery(UsersQuery);
}
Misc
Currently it's not tested on various cases. If you spot any issues with it, feel free to open issues!