### Install nitrogql CLI Source: https://nitrogql.vercel.app/cli Install the nitrogql CLI as a development dependency using npm. ```bash npm install --save-dev @nitrogql/cli ``` -------------------------------- ### Configure @nitrogql/rollup-plugin Source: https://nitrogql.vercel.app/references/rollup-plugin Example configuration for using the @nitrogql/rollup-plugin in a Rollup setup. Specify the configuration file and files to include for processing. ```javascript import nitrogql from "@nitrogql/rollup-plugin"; { plugins: [ nitrogql({ configFile: "./graphql.config.ts", include: ["**/*.graphql"], }), ], }; ``` -------------------------------- ### Install Nitrogql CLI and Core Types Source: https://nitrogql.vercel.app/guides/getting-started Install the Nitrogql CLI and the core types for TypedDocumentNode using npm. This is a prerequisite for using Nitrogql in your project. ```bash npm install --save-dev @nitrogql/cli @graphql-typed-document-node/core ``` -------------------------------- ### Generate Server GraphQL Schema Example Source: https://nitrogql.vercel.app/configuration/options An example of the generated TypeScript code when `serverGraphqlOutput` is configured. This file contains the schema as a string. ```typescript // ./app/generated/graphql.ts export const schema = ` scalar String scalar Boolean # ... type Query { # ... } # ... `; ``` -------------------------------- ### Install Webpack Loader for Nitrogql Source: https://nitrogql.vercel.app/guides/getting-started Install the Nitrogql loader for webpack if you are using webpack-based build tools. This allows webpack to process .graphql files. ```bash npm install --save-dev @nitrogql/graphql-loader ``` -------------------------------- ### Install Rollup Plugin for Nitrogql Source: https://nitrogql.vercel.app/guides/getting-started Install the Nitrogql plugin for Rollup if you are using Rollup-based build tools. This enables Rollup to handle .graphql files. ```bash npm install --save-dev @nitrogql/rollup-plugin ``` -------------------------------- ### Organizing Query and Mutation Resolvers Separately Source: https://nitrogql.vercel.app/guides/using-graphql Example of organizing query and mutation resolvers into separate constants before combining them. ```typescript const queryResolvers: Resolvers["Query"] = { // ... }; const mutationResolvers: Resolvers["Mutation"] = { // ... }; const resolvers = { Query: queryResolvers, Mutation: mutationResolvers, // ... }; ``` -------------------------------- ### Basic Apollo Server Setup with Generated Resolver Types Source: https://nitrogql.vercel.app/guides/using-graphql Set up an Apollo Server using generated schema and resolver types from Nitrogql for type-safe server-side development. ```typescript import { ApolloServer } from "@apollo/server"; // server GraphQL schema file import { schema } from "@/app/generated/graphql"; // resolver types import { Resolvers } from "@/app/generated/resolvers"; // Context is an object that is passed to all resolvers. // It is created per request. type Context = {}; // define all resolvers. const resolvers: Resolvers = { Query: { todos: async () => { /* ... */ } }, Mutation: { toggleTodos: async (_, variables) => { /* ... */ } }, // ... }; const server = new ApolloServer({ typeDefs: schema, resolvers, }); // ... ``` -------------------------------- ### NitrogqlConfig Example Source: https://nitrogql.vercel.app/references/nitrogql-cli Defines the structure for the entire configuration object exported by `graphql.config.ts`. Use this to specify schema and document paths, and nitrogql extensions. ```typescript import type { NitrogqlConfig } from "@nitrogql/cli"; const config: NitrogqlConfig = { schema: "src/schema/*.graphql", documents: "src/app/**/*.graphql", extensions: { nitrogql: { plugins: ["nitrogql:model-plugin"], // ... } } }; export default config; ``` -------------------------------- ### NitrogqlExtension Example Source: https://nitrogql.vercel.app/references/nitrogql-cli Defines the type for the `extensions.nitrogql` property in the config file. This is useful for integrating nitrogql with other tools by specifying its plugins. ```typescript import type { NitrogqlExtension } from "@nitrogql/cli"; const nitrogql: NitrogqlExtension = { plugins: ["nitrogql:model-plugin"], // ... }; const config = { schema: "src/schema/*.graphql", documents: "src/app/**/*.graphql", extensions: { nitrogql, // ... } }; export default config; ``` -------------------------------- ### Example Usage of Partial Resolvers Source: https://nitrogql.vercel.app/guides/organizing-resolver-definitions Demonstrates how to use the `partialResolvers` helper to define resolvers for Query, Mutation, and specific types like 'Todo'. This approach allows defining only the necessary resolvers within a module. ```typescript export const todosResolvers = partialResolvers({ Query: { todos: async () => { // ... } }, Mutation: { toggleTodos: async (_, variables) => { // ... } }, Todo: { // ... } }); ``` -------------------------------- ### Define GraphQL Operations Source: https://nitrogql.vercel.app/guides/using-graphql Example of a GraphQL query operation to fetch 'todos' with specific fields. Place operation files in the directory specified by the 'documents' configuration. ```graphql query getTodos { todos { id body createdAt finishedAt } } ``` -------------------------------- ### Rollup Configuration for Nitrogql Plugin Source: https://nitrogql.vercel.app/guides/getting-started Example Rollup configuration to include the @nitrogql/rollup-plugin. This plugin is configured to include all .graphql files in the build process. ```javascript import nitrogql from "@nitrogql/rollup-plugin"; export default { plugins: [ nitrogql({ include: ["**/*.graphql"], }), ], }; ``` -------------------------------- ### Define Top-Level and Type Resolvers Source: https://nitrogql.vercel.app/references/resolvers-file Example of how to define resolvers for top-level queries, mutations, and specific types like 'User'. Ensure you import `Resolvers` from the generated file. ```typescript import { Resolvers } from "./generated/resolvers"; type Context = {}; const resolvers: Resolvers = { // resolvers for top-level queries and mutations Query: { /* ... */ }, Mutation: { /* ... */ }, // resolvers for types User: { /* ... */ }, }; ``` -------------------------------- ### Example Usage of Resolver Merging Source: https://nitrogql.vercel.app/guides/organizing-resolver-definitions Shows how to use the `mergeResolvers` helper to combine resolvers from different modules (e.g., `sessionResolvers`, `todosResolvers`) into a single `resolvers` object. Explicitly typing with `: Resolvers` ensures all required resolvers are defined. ```typescript import { Resolvers } from "@/app/generated/resolvers"; import { Context } from "@/app/context"; import { sessionResolvers } from "./session"; import { todosResolvers } from "./todos"; // Note: `: Resolvers` is important to guarantee that you // defined all required resolvers. const resolvers: Resolvers = mergeResolvers([ sessionResolvers, todosResolvers, ]); ``` -------------------------------- ### Default Export for Operation Example Source: https://nitrogql.vercel.app/configuration/options Controls whether a generated operation document is exported as a default export. Default is true. ```javascript // defaultExportForOperation: true import GetUserQuery from "./app/graphql/queries/getUser.graphql"; ``` ```javascript // defaultExportForOperation: false import { GetUserQuery } from "./app/graphql/queries/getUser.graphql"; ``` -------------------------------- ### Define GraphQL Schema Source: https://nitrogql.vercel.app/guides/using-graphql Example of a GraphQL schema definition for a 'Todo' item. This defines the structure and types for your GraphQL API. ```graphql "One todo item." type Todo { "ID of this todo item." id: ID! "Contents of this todo item." body: String! "When not null, date when this item was marked done." finishedAt: Date "Date when this item was created." createdAt: Date! } ``` -------------------------------- ### Resolver Input Type Example Source: https://nitrogql.vercel.app/configuration/scalar-types Demonstrates how the `id` argument in a resolver is typed as its `resolverInput` variant (string) when using the `ID` scalar type. ```graphql type Query { getUser(id: ID!): User! } ``` ```typescript const getUser: Resolvers["Query"]["getUser"] = async ( _, { id }, ) => { // `id` is typed as its `resolverInput` variant (string) // ... }; ``` -------------------------------- ### Resolver Output Type Example Source: https://nitrogql.vercel.app/configuration/scalar-types Illustrates how the return value of a resolver is typed as its `resolverOutput` variant (string | number) for the `ID` scalar type. ```graphql type Query { me: User! } ``` ```typescript const me: Resolvers["Query"]["me"] = async () => { return { // `id` is typed as its `resolverOutput` variant (string | number) id: 1, // ... }; }; ``` -------------------------------- ### GraphQL ID Type Example Source: https://nitrogql.vercel.app/blog/release-1.6 Illustrates how GraphQL ID values, which can be integers or strings, are serialized as strings when sent to the client. ```json { id: 123, // ID name: "Alice", // String } ``` ```json { "id": "123", "name": "Alice" } ``` -------------------------------- ### Operation Output Type Example Source: https://nitrogql.vercel.app/configuration/scalar-types Demonstrates how the `id` field in the data returned from a client-side operation is typed as its `operationOutput` variant (string). ```graphql query Me { me { id # ... } } ``` ```typescript const result = await yourClient.query({ query: MeQuery, }); // `id` is typed as its `operationOutput` variant (string) const id = result.data.me.id; ``` -------------------------------- ### Variables Type Export Example Source: https://nitrogql.vercel.app/configuration/options Controls whether a generated operation variables type is exported. Default is false. ```javascript // variablesType: true import { GetUserVariables } from "./app/graphql/queries/getUser.graphql"; ``` -------------------------------- ### Operation Result Type Export Example Source: https://nitrogql.vercel.app/configuration/options Controls whether a generated operation result type is exported. Default is false. ```javascript // operationResultType: true import { GetUserResult } from "./app/graphql/queries/getUser.graphql"; ``` -------------------------------- ### Operation Input Type Example Source: https://nitrogql.vercel.app/configuration/scalar-types Shows how the `id` variable in a GraphQL operation is typed as its `operationInput` variant (string | number) when passed to a client-side query. ```graphql query GetUser($id: ID!) { getUser(id: $id) { # ... } } ``` ```typescript const result = await yourClient.query({ query: GetUserQuery, variables: { // `id` is typed as its `operationInput` variant (string | number) id: 1, }, }); ``` -------------------------------- ### Generated Schema Runtime Code Example Source: https://nitrogql.vercel.app/configuration/options Illustrates the generated code for enums when `emitSchemaRuntime` is enabled. The `UserType` enum shows both the type definition and the runtime object. ```typescript // Always emitted for enums export type UserType = "NormalUser" | "PremiumUser"; // Emitted only if emitSchemaRuntime is true export const UserType = { NormalUser: "NormalUser", PremiumUser: "PremiumUser", } as const; ``` -------------------------------- ### Capitalize Operation Names Example Source: https://nitrogql.vercel.app/configuration/options Controls whether the first letter of operation names is capitalized. This affects how operations are imported in editors. Default is true. ```javascript import GetUserQuery from "./app/graphql/queries/getUser.graphql"; ``` -------------------------------- ### Configure Custom Scalar Type Mapping Source: https://nitrogql.vercel.app/configuration/options Map GraphQL scalar types to TypeScript types using `scalarTypes`. This example shows mapping a custom `Date` scalar to a `string` type. ```yaml extensions: nitrogql: generate: type: scalarTypes: Date: string ``` -------------------------------- ### Basic nitrogql CLI Usage Source: https://nitrogql.vercel.app/cli General syntax for using nitrogql commands and options. ```bash nitrogql [options] ``` -------------------------------- ### Check GraphQL Files Source: https://nitrogql.vercel.app/guides/using-graphql Command to statically check all GraphQL files in your project for validity. It exits with code 0 on success or prints errors and exits with code 1. ```bash npx nitrogql check ``` -------------------------------- ### Basic nitrogql Configuration Source: https://nitrogql.vercel.app/guides/migrating-from-graphql-codegen Set up the basic nitrogql configuration file, reusing schema and documents options from GraphQL Code Generator. ```yaml # graphql.config.yaml schema: src/schema/*.graphql documents: src/app/**/*.graphql ``` -------------------------------- ### Configure Webpack with GraphQL Loader Source: https://nitrogql.vercel.app/references/graphql-loader Set up your webpack.config.js to use the @nitrogql/graphql-loader for .graphql files. Specify the path to your GraphQL configuration file. ```javascript module.exports = { module: { rules: [ { test: /.graphql$/, loader: "@nitrogql/graphql-loader", options: { configFile: "./graphql.config.yaml", }, }, ], }, }; ``` -------------------------------- ### Using Generated Server GraphQL Schema Source: https://nitrogql.vercel.app/references/server-graphql-file Import the generated schema and resolvers to initialize an Apollo Server. This demonstrates the simplified process of supplying your schema to a server. ```typescript import { schema } from "./generated/serverGraphql"; import { Resolvers } from "./generated/resolvers"; import { ApolloServer } from "apollo-server"; const resolvers: Resolvers<{}> = { /* ... */ }; const server = new ApolloServer({ typeDefs: schema, resolvers, }); ``` -------------------------------- ### Basic Jest Configuration for GraphQL Files Source: https://nitrogql.vercel.app/references/jest-transform Configure Jest to use @nitrogql/jest-transform for .graphql files, specifying a configuration file. ```javascript { "transform": { "^.+\.graphql$": ["@nitrogql/jest-transform", { "configFile": path.resolve(__dirname, "nitrogql.config.js") }] } } ``` -------------------------------- ### Generate Types with Custom Config File Source: https://nitrogql.vercel.app/cli Use the 'generate' command with a specific configuration file path using the --config-file option. ```bash npx nitrogql generate --config-file ./path/to/config.yaml ``` -------------------------------- ### Configure Server GraphQL Output Source: https://nitrogql.vercel.app/configuration/options When `generate.serverGraphqlOutput` is set, the `generate` command creates a single TypeScript file containing the entire GraphQL schema, suitable for creating a GraphQL server. ```yaml schema: "./schema/*.graphql" documents: - "./app/**/*.graphql" extensions: nitrogql: generate: serverGraphqlOutput: "./app/generated/graphql.ts" ``` -------------------------------- ### Jest Configuration with CommonJS Support using ts-jest Source: https://nitrogql.vercel.app/references/jest-transform Set up Jest to handle .graphql files and transform the generated ES modules to CommonJS using ts-jest as an additional transformer. ```javascript { "transform": { "^.+.tsx?": ["ts-jest", { isolatedModules: true }], "^.+\.graphql$": ["@nitrogql/jest-transform", { "configFile": path.resolve(__dirname, "nitrogql.config.yml"), // Use the additionalTransformer option to apply ts-jest to the output. "additionalTransformer": ["ts-jest", { isolatedModules: true }], // ts-jest expects .ts files, so we need to change the file extension // by applying the additionalTransformerFilenameSuffix option. "additionalTransformerFilenameSuffix": ".ts" }] }, } ``` -------------------------------- ### Import All Fragments Source: https://nitrogql.vercel.app/references/syntax-import Import all fragments defined in a GraphQL document using the wildcard '*'. This is useful when you need to access all available fragments from a shared file. ```graphql #import * from "./path/to/file.graphql" ``` -------------------------------- ### GraphQL Server Package Configuration Source: https://nitrogql.vercel.app/guides/monorepo Configuration for a GraphQL server package. Generates resolver types and server-side GraphQL types. ```yaml schema: ../schema-package/schema/*.graphql extensions: nitrogql: plugins: - "nitrogql:model-plugin" generate: schemaModuleSpecifier: "@your-org/schema-package" resolversOutput: ./dist/resolvers.d.ts serverGraphqlOutput: ./dist/graphql.ts ``` -------------------------------- ### Implement Resolver with ResolverOutput Type Source: https://nitrogql.vercel.app/references/resolvers-file Shows how to implement a resolver for the 'me' query, where the return object's type is `ResolverOutput<"User">`. The `user` parameter in the 'email' resolver also has the type `ResolverOutput<"User">`. ```typescript import { Resolvers, ResolverOutput } from "./generated/resolvers"; type Context = {}; const queryResolvers: Resolvers["Query"] = { /** get the current user */ me: () => { // the type of the returned object is ResolverOutput<"User"> return { id: "1", name: "John Doe", }; } }; const userResolvers: Resolvers<{}>["User"] = { email: async (user) => { // the type of `user` is ResolverOutput<"User"> const email = await getEmail(user.id); } } ``` -------------------------------- ### Import Specific Fragments Source: https://nitrogql.vercel.app/references/syntax-import Import two fragments, Fragment1 and Fragment2, from a specified relative path. The imported fragments become available for use in the current document. Ensure the target file defines these fragments. ```graphql #import Fragment1, Fragment2 from "./path/to/file.graphql" ``` -------------------------------- ### Generate TypeScript Files Source: https://nitrogql.vercel.app/guides/using-graphql Command to generate TypeScript definition files from GraphQL schemas and operations. This command also implies 'check'. ```bash npx nitrogql generate ``` -------------------------------- ### Configure Rollup for .graphql Files Source: https://nitrogql.vercel.app/guides/migrating-from-graphql-codegen Integrate the `@nitrogql/rollup-plugin` into your Rollup configuration to handle `.graphql` files, including specifying the configuration file and files to include. ```javascript // rollup.config.js import graphql from "@nitrogql/rollup-plugin"; export default { // ... plugins: [ // ... graphql({ // path to your nitrogql configuration file configFile: "./graphql.config.yaml", include: ["**/*.graphql"], }), ], }; ``` -------------------------------- ### Valid and Invalid #import Placement Source: https://nitrogql.vercel.app/references/syntax-import Demonstrates the correct placement of the #import syntax at the top level of an operation document. Importing within other constructs like query bodies will result in a syntax error. ```graphql #import Fragment1 from "./path/to/file.graphql" # ↑ This is valid query { #import Fragment2 from "./path/to/file.graphql" # ↑ This is invalid! # ... } ``` -------------------------------- ### Watch GraphQL Files and Generate Types Automatically with chokidar-cli Source: https://nitrogql.vercel.app/guides/using-graphql Use chokidar-cli to watch for changes in .graphql files and automatically run the nitrogql generate command. ```bash chokidar '**/*.graphql' --initial --command 'npx nitrogql generate' ``` -------------------------------- ### Configure nitrogql:model Plugin Source: https://nitrogql.vercel.app/references/plugin-model Add the nitrogql:model-plugin to your configuration file's plugins array to enable its functionality. ```yaml schema: ./schema/*.graphql extensions: nitrogql: plugins: - "nitrogql:model-plugin" # ... ``` -------------------------------- ### Configure VSCode Run on Save for Automatic Type Generation Source: https://nitrogql.vercel.app/guides/using-graphql Configure the VSCode Run on Save extension to automatically execute the nitrogql generate command when .graphql files are saved. ```json { "emeraldwalk.runonsave": { "commands": [ { "match": "\.graphql$", "cmd": "npx nitrogql generate" } ] } } ``` -------------------------------- ### Importing and Combining Module Resolvers Source: https://nitrogql.vercel.app/guides/organizing-resolver-definitions Import individual resolvers from different modules and combine them into the main resolver object. Assumes Context is defined in '@/app/context'. ```typescript import { Resolvers } from "@/app/generated/resolvers"; import { Context } from "@/app/context"; import { meResolver } from "./session"; import { todosResolver, toggleTodosResolver, todoResolvers } from "./todos"; // define all resolvers. const resolvers: Resolvers = { Query: { me: meResolver, todos: todosResolver, }, Mutation: { toggleTodos: toggleTodosResolver, }, Todo: todoResolvers, // ... }; ``` -------------------------------- ### Specify Schema and Operations Location Source: https://nitrogql.vercel.app/configuration/options Use `schema` and `documents` to define the paths to your schema and operation files. These fields accept glob patterns and can be a string or an array of strings. `schema` is always required. ```yaml schema: "./schema/*.graphql" documents: - "./app/**/*.graphql" - "./common/**/*.graphql" ``` -------------------------------- ### Configure Nitrogql Plugins Source: https://nitrogql.vercel.app/configuration/options The `plugins` field within `extensions.nitrogql` is used to specify built-in plugins. Currently, only built-in plugins are supported. ```yaml extensions: nitrogql: plugins: - nitrogql:model-plugin ``` -------------------------------- ### Basic Nitrogql Configuration Source: https://nitrogql.vercel.app/guides/getting-started A minimal configuration file for Nitrogql, specifying the paths for your GraphQL schema and documents. This file should be named graphql.config.yaml. ```yaml schema: ./schema/*.graphql documents: ./app/**/*.graphql ``` -------------------------------- ### Schema Package Configuration Source: https://nitrogql.vercel.app/guides/monorepo Configuration for a package containing GraphQL schemas. Generates schema definition types. ```yaml schema: ./schema/*.graphql extensions: nitrogql: generate: schemaOutput: ./dist/schema.d.ts ``` -------------------------------- ### Configure TypeScript to Allow Arbitrary Extensions Source: https://nitrogql.vercel.app/guides/using-graphql Adjust your tsconfig.json to allow importing files with arbitrary extensions, such as .graphql files. ```json { "compilerOptions": { // ... "allowArbitraryExtensions": true, // ... } } ``` -------------------------------- ### Configure nitrogql for Code Generation Source: https://nitrogql.vercel.app/guides/using-graphql Configuration snippet specifying output paths for generated schema, resolver, and server GraphQL schema files. Operation type definition files are generated next to operation files. ```yaml schema: ./schema/*.graphql documents: extensions: nitrogql: generate: # Specify the location of generated schema file. schemaOutput: ./src/generated/schema.d.ts # Specify the location of generated resolver file. resolversOutput: ./src/generated/resolvers.d.ts # Specify the location of generated server GraphQL schema file. serverGraphqlOutput: ./src/generated/graphql.ts ``` -------------------------------- ### Advanced Scalar Type Mapping Options Source: https://nitrogql.vercel.app/configuration/options Demonstrates advanced ways to specify scalar type mappings, including separate types for sending and receiving, and for resolver/operation inputs/outputs. ```yaml scalarTypes: # 1. Specify as a single string Date: string # 2. Specify as a pair of send and receive types Date: send: string | Date receive: string # 3. Specify as a set of four types Date: resolverInput: string resolverOutput: string | Date operationInput: string | Date operationOutput: string ``` -------------------------------- ### Operation Package Configuration Source: https://nitrogql.vercel.app/guides/monorepo Configuration for packages that generate code for GraphQL operations. Requires schema definition and operation document paths. ```yaml schema: ../schema-package/schema/*.graphql documents: ./app/**/*.graphql extensions: nitrogql: generate: schemaModuleSpecifier: "@your-org/schema-package" ``` -------------------------------- ### ES Module JavaScript Configuration Source: https://nitrogql.vercel.app/configuration/file-name Use this format for ES Module configurations in JavaScript. Ensure the configuration object is default-exported. ```javascript import type { NitrogqlConfig } from "@nitrogql/cli"; const config: NitrogqlConfig = { schema: "./schema/*.graphql", documents: ["./app/**/*.graphql", "./common/**/*.graphql"], // ... }; export default config; ``` -------------------------------- ### Default Naming Conventions for Generated Code Source: https://nitrogql.vercel.app/configuration/options Shows the default settings for naming generated types and variables, such as `operationResultTypeSuffix` and `variablesTypeSuffix`. ```yaml extensions: nitrogql: generate: name: # default values capitalizeOperationNames: true operationResultTypeSuffix: Result variablesTypeSuffix: Variables fragmentTypeSuffix: '' queryVariableSuffix: Query mutationVariableSuffix: Mutation subscriptionVariableSuffix: Subscription fragmentVariableSuffix: '' ``` -------------------------------- ### Configure Resolvers Output Path Source: https://nitrogql.vercel.app/configuration/options Set `generate.resolversOutput` to generate a TypeScript file with type definitions for resolvers, enabling type-safe resolver writing. Requires `generate.schemaOutput` or `generate.schemaModuleSpecifier` to be configured. ```yaml schema: "./schema/*.graphql" extensions: nitrogql: generate: resolversOutput: "./app/generated/resolvers.ts" ``` -------------------------------- ### Avoid Importing Generated User Type Directly Source: https://nitrogql.vercel.app/references/schema-file Demonstrates the recommended practice of defining internal data structures with manually written types instead of directly importing generated types from the schema package. ```typescript // ❌ Don't do this import { User } from "@your-org/schema-package"; export const ShowUser: React.FC<{ user: User; }> = ({ user }) => { // ... }; // ✅ Do this export const ShowUser: React.FC<{ user: { id: string; name: string; }; }> = ({ user }) => { // ... }; ``` -------------------------------- ### Import GraphQL file in TypeScript Source: https://nitrogql.vercel.app/ Import .graphql files directly from .ts files for client-side code. This requires a webpack loader or rollup plugin. ```typescript import MyQuery from "./query.graphql"; ``` -------------------------------- ### Configure Schema Output and Runtime Enums Source: https://nitrogql.vercel.app/guides/migrating-from-graphql-codegen Configure nitrogql to specify the schema output path and enable runtime enum emission, similar to GraphQL Code Generator's typescript plugin. ```yaml # GraphQL Code Generator configuration generates: path/to/schema.ts: plugins: - typescript config: # ... # corresponding nitrogql configuration (graphql.config.yaml) schema: src/schema/*.graphql documents: src/app/**/*.graphql extensions: nitrogql: generate: schemaOutput: path/to/schema.ts emitSchemaRuntime: true ``` -------------------------------- ### Configure nitrogql for Server-Side Resolver Output Source: https://nitrogql.vercel.app/guides/migrating-from-graphql-codegen Set the `generate.resolverOutput` option in nitrogql to specify the path for generated resolver type definitions, mirroring GraphQL Code Generator's `typescript-resolvers` plugin. ```yaml # GraphQL Code Generator configuration generates: src/generated/resolvers.ts: plugins: - typescript-resolvers config: # ... # corresponding nitrogql configuration (graphql.config.yaml) schema: src/schema/*.graphql documents: src/app/**/*.graphql extensions: nitrogql: generate: # ... resolverOutput: src/generated/resolvers.ts ``` -------------------------------- ### VS Code File Nesting for Generated Files Source: https://nitrogql.vercel.app/faq Configure VS Code's file nesting feature to group generated GraphQL type definition files with their source .graphql files. This helps organize your project by collapsing generated files. ```json { "explorer.fileNesting.enabled": true, "explorer.fileNesting.patterns": { "*.graphql": "${capture}.d.graphql.ts,${capture}.d.graphql.ts.map" } } ``` -------------------------------- ### Change output extension to .graphql.ts Source: https://nitrogql.vercel.app/guides/migrating-from-graphql-codegen Adjust GraphQL Code Generator to output files with a `.graphql.ts` extension instead of `.generated.ts`. This facilitates direct imports from `.graphql` files after migrating to nitrogql. ```yaml # codegen.yml generates: src/: # ... presetConfig: extension: .graphql.ts ``` -------------------------------- ### Single File Resolver Definition Source: https://nitrogql.vercel.app/guides/organizing-resolver-definitions For small schemas, all resolvers can be defined in a single file. Ensure the Resolvers type is imported and the Context type is defined. ```typescript import { Resolvers } from "@/app/generated/resolvers"; // Context is an object that is passed to all resolvers. // It is created per request. type Context = {}; // define all resolvers. const resolvers: Resolvers = { Query: { me: async () => { /* ... */ }, todos: async () => { /* ... */ } }, Mutation: { toggleTodos: async (_, variables) => { /* ... */ } }, User: { // ... }, }; ``` -------------------------------- ### Enable Runtime Schema Generation Source: https://nitrogql.vercel.app/configuration/options Set `emitSchemaRuntime` to `true` to include runtime code for generated schema types, primarily for enums. Note that `schemaOutput` cannot be a `.d.ts` file when this is enabled. ```yaml extensions: nitrogql: generate: schemaOutput: "./app/generated/schema.ts" emitSchemaRuntime: true ``` -------------------------------- ### Resolver Type Comparison: GraphQL Code Generator vs. nitrogql Source: https://nitrogql.vercel.app/guides/migrating-from-graphql-codegen Illustrates the difference in how GraphQL Code Generator and nitrogql generate resolver types. nitrogql uses a single generic 'Resolvers' type, while GraphQL Code Generator exports separate types like 'Resolvers' and 'UserResolvers'. ```typescript // GraphQL Code Generator import type { Resolvers, UserResolvers } from "~/generated/resolvers"; const userResolvers: UserResolvers = { // ... }; const resolvers: Resolvers = { User: userResolvers, // ... }; ``` ```typescript // nitrogql import type { Resolvers } from "~/generated/resolvers"; const userResolvers: Resolvers["User"] = { // ... }; const resolvers: Resolvers = { User: userResolvers, // ... }; ``` -------------------------------- ### Nitrogql Generate Export Configuration Source: https://nitrogql.vercel.app/configuration/options Default settings for exporting generated types and variables. Includes options for default export for operations, and visibility of operation result and variables types. ```yaml extensions: nitrogql: generate: export: defaultExportForOperation: true operationResultType: false variablesType: false ``` -------------------------------- ### Allow File System Access Outside Current Directory Source: https://nitrogql.vercel.app/cli Use the NITROGQL_FS_SCOPE environment variable to grant the CLI access to files outside the current directory, demonstrated with the 'check' command. ```bash NITROGQL_FS_SCOPE=../ npx nitrogql check --config-file ../graphql.config.yaml ``` -------------------------------- ### CLI Output Interface Definition Source: https://nitrogql.vercel.app/cli Defines the structure of the JSON output from the nitrogql CLI, including error, check, and generate fields. ```typescript interface CLIOutput { /** * Exists when a command fails. */ error?: { /** * Command name that had error. */ command: string | null; /** * Error message. */ message: string; } /** * Exists when the 'check' command is run. */ check?: { /** * List of errors. * Empty when the check is successful. */ errors: { fileType: "schema" | "operation"; file?: { path: string; // line and column are 0-indexed line: number; column: number; } message: string; }[] } /** * Exists when the 'generate' command is run. */ generate?: { /** * List of output files. */ files: { fileType: | "schemaTypeDefinition" | "schemaTypeDefinitionSourceMap" | "operationTypeDefinition" | "operationTypeDefinitionSourceMap"; path: string; }[]; } } ``` -------------------------------- ### Defining Resolvers Per Type Source: https://nitrogql.vercel.app/guides/organizing-resolver-definitions Split resolver definitions by GraphQL type for better organization. Each type's resolvers are defined separately and then combined. ```typescript import { Resolvers } from "@/app/generated/resolvers"; type Context = {}; const queryResolvers: Resolvers["Query"] = { me: async () => { /* ... */ }, todos: async () => { /* ... */ } }; const mutationResolvers: Resolvers["Mutation"] = { toggleTodos: async (_, variables) => { /* ... */ } }; const userResolvers: Resolvers["User"] = { // ... }; // define all resolvers. const resolvers: Resolvers = { Query: queryResolvers, Mutation: mutationResolvers, User: userResolvers, }; ``` -------------------------------- ### Exporting Individual Resolvers from Modules Source: https://nitrogql.vercel.app/guides/organizing-resolver-definitions Organize resolvers into modules based on related functionality. Each resolver function is exported individually. ```typescript import { Resolvers } from "@/app/generated/resolvers"; import { Context } from "@/app/context"; export const todosResolver: Resolvers["Query"]["todos"] = async () => { // ... }; export const toggleTodosResolver: Resolvers["Mutation"]["toggleTodos"] = async (_, variables) => { // ... }; export const todoResolvers: Resolvers["Todo"] = { // ... }; ``` -------------------------------- ### Configure Schema Module Specifier Source: https://nitrogql.vercel.app/configuration/options Use `schemaModuleSpecifier` to define a consistent import path for generated schema types across operations. This is particularly useful in monorepos. ```yaml schema: "./schema/*.graphql" documents: - "./app/**/*.graphql" - "./common/**/*.graphql" extensions: nitrogql: generate: schemaOutput: "./app/generated/schema.ts" schemaModuleSpecifier: "@/generated/schema" ``` -------------------------------- ### Configure nitrogql for Client-Side Operation Output Source: https://nitrogql.vercel.app/guides/migrating-from-graphql-codegen Configure nitrogql's `generate` options to match GraphQL Code Generator's `typescript-operations` plugin behavior, particularly for operation result types and variable types. ```yaml schema: src/schema/*.graphql documents: src/app/**/*.graphql extensions: nitrogql: generate: schemaOutput: path/to/schema.ts emitSchemaRuntime: true # add below export: defaultExportForOperation: false variablesType: true operationResultType: true name: queryVariableSuffix: Document mutationVariableSuffix: Document subscriptionVariableSuffix: Document ``` -------------------------------- ### Import Fragment Object Source: https://nitrogql.vercel.app/references/operation-file Import a fragment object, which is exported as a named export. This object represents the shape of a query response matching the fragment. ```typescript import { todoFragment } from "./todo.graphql"; ``` -------------------------------- ### Configure Schema Output Path Source: https://nitrogql.vercel.app/configuration/options Set `generate.schemaOutput` to specify where generated schema types should be outputted. This generated file is depended upon by generated operation types. ```yaml schema: "./schema/*.graphql" documents: - "./app/**/*.graphql" - "./common/**/*.graphql" extensions: nitrogql: generate: schemaOutput: "./app/generated/schema.ts" ``` -------------------------------- ### Access Specific Resolver Types Source: https://nitrogql.vercel.app/references/resolvers-file Demonstrates how to access the resolver type for a specific field, such as 'Query', using TypeScript's type inference. ```typescript import { Resolvers } from "./generated/resolvers"; const queryResolvers: Resolvers["Query"] = { /* ... */ }; ``` -------------------------------- ### Configure Nitrogql to Use GraphQL Scalars Plugin Source: https://nitrogql.vercel.app/references/plugin-graphql-scalars Add the 'nitrogql:graphql-scalars-plugin' to your nitrogql configuration to enable integration with GraphQL Scalars. ```yaml schema: - ./schema/*.graphql - ./schema/scalars.ts extensions: nitrogql: plugins: - "nitrogql:graphql-scalars-plugin" # ... ``` -------------------------------- ### Define Partial Resolvers Helper Source: https://nitrogql.vercel.app/guides/organizing-resolver-definitions This helper function allows defining only a subset of resolvers for a given type, reducing boilerplate and improving readability. It accepts a partial resolver definition and returns it as-is, preserving type information. ```typescript import { Resolvers } from "@/app/generated/resolvers"; import { Context } from "@/app/context"; function partialResolvers]: Partial[K]>; }> R>(resolvers: R): R { return resolvers; } ``` -------------------------------- ### Subscription Variable Suffix Source: https://nitrogql.vercel.app/configuration/options Defines the suffix for the generated subscription variable. Default is "Subscription". ```graphql subscription onUserCreated ``` -------------------------------- ### Fragment Type Suffix Source: https://nitrogql.vercel.app/configuration/options Defines the suffix for the generated fragment type. Default is an empty string. ```graphql fragment PartialUser ``` -------------------------------- ### Send/Receive Form for ID Scalar Source: https://nitrogql.vercel.app/configuration/scalar-types Configures the ID scalar to accept string or number when sending, and string when receiving. ```yaml scalarTypes: ID: send: string | number receive: string ``` -------------------------------- ### Resolver Output Position Type for ID Source: https://nitrogql.vercel.app/blog/release-1.6 Shows how the 'id' field is handled in the output position of a resolver. The type of 'user.id' can be string or number before serialization. ```typescript const userResolver: Resolvers["Query"]["user"] = async ( _, { id }, ) => { // ... return { id: user.id, // ^ `id` used in the resolver output position name: user.name, }; } ``` -------------------------------- ### Import Results and Variables Source: https://nitrogql.vercel.app/references/operation-file Import named exports for Result and Variables types when the 'generate.export' option is enabled. This allows direct access to the response and variable types. ```typescript import { getTodosQuery, type GetTodosQueryResult, type GetTodosQueryVariables } from "./operation.graphql"; ``` -------------------------------- ### Configure Operation Type Generation Mode Source: https://nitrogql.vercel.app/configuration/options The `generate.mode` option configures how types for operations are generated. Possible values include `with-loader-ts-5.0`, `with-loader-ts-4.0`, and `standalone-ts-4.0`. The default is `with-loader-ts-5.0`. ```yaml schema: "./schema/*.graphql" documents: - "./app/**/*.graphql" - "./common/**/*.graphql" extensions: nitrogql: generate: mode: with-loader-ts-5.0 schemaOutput: "./app/generated/schema.ts" ``` -------------------------------- ### Resolver Input Position Type for ID Source: https://nitrogql.vercel.app/blog/release-1.6 Demonstrates the type of the 'id' argument in a resolver function when it's used in the input position. The server coerces the input to a string. ```typescript const userResolver: Resolvers["Query"]["user"] = async ( _, { id }, // ^ `id` used in the resolver input position ) => { // ... } ``` -------------------------------- ### GraphQL Code Generator Scalar Mapping (ID) Source: https://nitrogql.vercel.app/blog/release-1.6 Illustrates how scalar type mappings are configured in GraphQL Code Generator, using 'input' and 'output' semantics which differ from Nitrogql's 'send/receive'. ```yaml # GraphQL code generator config ID: input: string output: string | number ``` -------------------------------- ### Define GraphQL Scalars Types in TypeScript Source: https://nitrogql.vercel.app/references/plugin-graphql-scalars Create a TypeScript file that default-exports a GraphQLSchema instance including GraphQL Scalars types like DateTimeResolver. This allows nitrogql to automatically recognize and map these types. ```typescript import { GraphQLSchema } from "graphql"; import { DateTimeResolver } from "graphql-scalars"; export default new GraphQLSchema({ types: [DateTimeResolver], }); ``` -------------------------------- ### Import Default Operation Object Source: https://nitrogql.vercel.app/references/operation-file Import the operation object when it's exported as a default export. This is the default behavior. ```typescript import getTodosQuery from "./getTodos.graphql"; ``` -------------------------------- ### Mutation Variable Suffix Source: https://nitrogql.vercel.app/configuration/options Defines the suffix for the generated mutation variable. Default is "Mutation". ```graphql mutation createUser ``` -------------------------------- ### Set enumsAsConst to true Source: https://nitrogql.vercel.app/guides/migrating-from-graphql-codegen Configure GraphQL Code Generator to use union types for enums instead of TypeScript's `enum` syntax by setting `enumsAsConst` to `true`. This improves compatibility with nitrogql's approach. ```yaml # codegen.yml config: enumsAsConst: true ``` -------------------------------- ### Separate Form for Date Scalar Source: https://nitrogql.vercel.app/configuration/scalar-types Defines distinct types for each of the four situations (resolverInput, resolverOutput, operationInput, operationOutput) for the Date scalar. ```yaml scalarTypes: Date: resolverInput: string resolverOutput: Date | string operationInput: string operationOutput: string ```