### Start Development Server (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Commands to start the development server for both Nitro and Nuxt projects using npm. ```bash npm run dev ``` ```bash npm run dev ``` -------------------------------- ### Example GraphQL Schema (GraphQL) Source: https://nitro-graphql.pages.dev/guide/installation Defines a basic GraphQL schema with a 'hello' query and a required empty mutation type. This serves as a starting point for your API. ```graphql type Query { hello: String! } type Mutation { _empty: String } ``` -------------------------------- ### Example Resolver (TypeScript) Source: https://nitro-graphql.pages.dev/guide/installation Provides a simple resolver for the 'hello' query, returning a greeting message. This demonstrates how to define query resolvers. ```typescript export const helloQuery = defineQuery({ hello: () => 'Hello from Nitro GraphQL!', }) ``` -------------------------------- ### Setup and Run Nitro GraphQL Locally Source: https://nitro-graphql.pages.dev/contributing/adding-features Commands to clone the repository, install dependencies using pnpm, and start the development server for Nitro GraphQL. ```bash git clone https://github.com/YOUR_USERNAME/nitro-graphql.git cd nitro-graphql pnpm install pnpm dev ``` -------------------------------- ### Manually Run Federation Playground Source: https://nitro-graphql.pages.dev/contributing/development-setup Provides steps to manually set up and run the Federation playground. This involves navigating to the playground directory, installing its dependencies, and starting the development server. ```bash cd playgrounds/federation pnpm install pnpm dev ``` -------------------------------- ### Manually Run Nuxt Playground Source: https://nitro-graphql.pages.dev/contributing/development-setup Provides steps to manually set up and run the Nuxt playground. This involves navigating to the playground directory, installing its dependencies, and starting the development server. ```bash cd playgrounds/nuxt pnpm install pnpm dev ``` -------------------------------- ### Bash Commands for Running E-Commerce API Source: https://nitro-graphql.pages.dev/examples/e-commerce-api Provides essential bash commands for managing the e-commerce API project. Includes commands for installing dependencies, starting the development server, building for production, and previewing the production build. The GraphQL endpoint is accessible at http://localhost:3000/api/graphql. ```bash # Install dependencies pnpm install # Development mode pnpm dev # Build for production pnpm build # Preview production pnpm preview Access the GraphQL endpoint at: `http://localhost:3000/api/graphql` ``` -------------------------------- ### Install Lucia Auth Dependency (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs the Lucia Auth library for authentication. ```bash # Lucia Auth pnpm add lucia ``` -------------------------------- ### Create Nitro Project (Bash) Source: https://nitro-graphql.pages.dev/guide/installation This snippet shows how to create a new Nitro project using npx and giget, and then navigate into the project directory. ```bash # Create a new Nitro project npx giget@latest nitro my-nitro-app cd my-nitro-app ``` -------------------------------- ### Install and Run VitePress Docs Locally (pnpm) Source: https://nitro-graphql.pages.dev/contributing/documentation Commands to install dependencies and start the local development server for VitePress documentation using pnpm. Assumes the user is in the `.docs` directory. ```bash cd .docs pnpm install cd .docs pnpm dev ``` -------------------------------- ### Install GraphQL Subscriptions Dependency (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs the GraphQL Yoga library, which includes support for subscriptions. ```bash # GraphQL Subscriptions (Yoga) pnpm add graphql-yoga # Already included with Yoga! ``` -------------------------------- ### Install Nitro GraphQL and GraphQL Yoga Source: https://nitro-graphql.pages.dev/guide/graphql-yoga Installs the necessary packages for using GraphQL Yoga with Nitro GraphQL. This includes `nitro-graphql`, `graphql-yoga`, and `graphql`. ```bash pnpm add nitro-graphql graphql-yoga graphql ``` -------------------------------- ### Install Prisma Dependencies (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs Prisma ORM and its CLI tool for database integration. ```bash # Prisma pnpm add prisma @prisma/client pnpm add -D prisma ``` -------------------------------- ### Create Nuxt Project (Bash) Source: https://nitro-graphql.pages.dev/guide/installation This snippet demonstrates how to initialize a new Nuxt project using npx nuxi and change the directory. ```bash # Create a new Nuxt project npx nuxi@latest init my-nuxt-app cd my-nuxt-app ``` -------------------------------- ### Install Nitro GraphQL Dependencies (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs Nitro GraphQL and its associated framework dependencies. Supports GraphQL Yoga (recommended) and Apollo Server. ```bash pnpm add nitro-graphql graphql-yoga graphql ``` ```bash pnpm add nitro-graphql @apollo/server @apollo/utils.withrequired @as-integrations/h3 graphql ``` -------------------------------- ### Install Dependencies (Bash) Source: https://nitro-graphql.pages.dev/guide/quick-start-nuxt Installs the necessary packages for Nitro GraphQL, graphql-yoga, and graphql in a Nuxt project. Supports pnpm, npm, and yarn package managers. ```bash pnpm add nitro-graphql graphql-yoga graphql ``` ```bash npm install nitro-graphql graphql-yoga graphql ``` ```bash yarn add nitro-graphql graphql-yoga graphql ``` -------------------------------- ### Test GraphQL API Query (GraphQL) Source: https://nitro-graphql.pages.dev/guide/installation A sample GraphQL query to test the 'hello' field. This query should be run against the `/api/graphql` endpoint. ```graphql query { hello } ``` -------------------------------- ### Install JWT Dependencies (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs the jsonwebtoken library and its type definitions for JWT-based authentication. ```bash # JWT pnpm add jsonwebtoken pnpm add -D @types/jsonwebtoken ``` -------------------------------- ### Example Page Markdown Structure Source: https://nitro-graphql.pages.dev/contributing/documentation A markdown template for 'Example' pages, showcasing complete implementations of concepts. Includes sections for overview, features, project structure, setup, implementation details (configuration, schema, resolvers), key concepts, and instructions to try it out. ```markdown # Example: Project Name Complete working example of [concept]. ## Overview What this example demonstrates. ## Features - Feature 1 - Feature 2 - Feature 3 ## Project Structure ``` project/ ├── server/ │ └── graphql/ ├── app/ └── nitro.config.ts ``` ## Setup ```bash # Clone and setup git clone https://github.com/example/repo cd repo pnpm install pnpm dev ``` ## Implementation ### Configuration ```typescript // nitro.config.ts ``` ### Schema ```graphql # schema.graphql ``` ### Resolvers ```typescript // resolvers.ts ``` ## Key Concepts Explain important patterns used. ## Try It Out 1. Start the server 2. Open GraphQL playground 3. Run example queries ## Source Code [View on GitHub](https://github.com/example/repo) ``` -------------------------------- ### Install VS Code GraphQL Extension (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs the official GraphQL extension for VS Code, providing syntax highlighting and autocomplete for GraphQL files. ```bash code --install-extension GraphQL.vscode-graphql ``` -------------------------------- ### Example Bash Script Source: https://nitro-graphql.pages.dev/contributing/documentation A simple bash script example, likely for setup or command execution within a recipe or example page. It's a placeholder for actual commands. ```bash # Commands ``` -------------------------------- ### Main Nitro Module Setup Source: https://nitro-graphql.pages.dev/contributing/architecture The core Nitro module setup function orchestrates the module's main tasks, including file watching, code generation, and route registration. It serves as the entry point for the Nitro GraphQL module. ```typescript import { defineNitroModule } from 'nitropack' export default defineNitroModule({ setup(nitro, options) { // 1. Setup file watching // 2. Scan and discover files // 3. Generate types // 4. Register routes // 5. Handle Nuxt integration } }) ``` -------------------------------- ### Install Apollo Federation Dependency (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs the @apollo/subgraph package for implementing Apollo Federation. ```bash # Apollo Federation pnpm add @apollo/subgraph ``` -------------------------------- ### Install Apollo Federation Dependencies Source: https://nitro-graphql.pages.dev/guide/apollo-federation Installs the necessary Apollo Server, Subgraph, and utility packages using pnpm. These are essential for enabling federation capabilities. ```bash pnpm add @apollo/server @apollo/subgraph @apollo/utils.withrequired @as-integrations/h3 graphql ``` -------------------------------- ### Example TypeScript Resolver with Auto-generated Types (TypeScript) Source: https://nitro-graphql.pages.dev/guide/installation Demonstrates how to import and use auto-generated server-side TypeScript types (like 'User') within a resolver function for type safety. ```typescript import type { User } from '#graphql/server' export const userQueries = defineQuery({ user: async (_, { id }): Promise => { // Fully typed! return await db.user.findUnique({ where: { id } }) }, }) ``` -------------------------------- ### Install Mongoose Dependency (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs Mongoose ODM for MongoDB integration. ```bash # Mongoose pnpm add mongoose ``` -------------------------------- ### Install Drizzle Dependencies (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Installs Drizzle ORM and its migration tool. ```bash # Drizzle pnpm add drizzle-orm pnpm add -D drizzle-kit ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://nitro-graphql.pages.dev/contributing/development-setup Installs all necessary project dependencies using pnpm. The `--frozen-lockfile` flag ensures that the exact versions specified in the lockfile are installed, preventing unexpected changes. ```bash pnpm install --frozen-lockfile ``` -------------------------------- ### Run Nitro GraphQL Playgrounds Source: https://nitro-graphql.pages.dev/contributing/development-setup Starts various playground environments for testing Nitro GraphQL. These commands typically require a separate terminal running `pnpm dev` for the module build watcher. ```bash pnpm playground:nitro ``` ```bash pnpm playground:nuxt ``` ```bash pnpm playground:federation ``` -------------------------------- ### Test GraphQL Mutations in Playground Source: https://nitro-graphql.pages.dev/guide/your-first-query Provides example GraphQL mutation requests for creating, updating, and deleting posts. These demonstrate how to send data to the server and receive responses. ```graphql mutation CreateNewPost { createPost(input: { title: "My First Post" content: "This is the content" authorId: "1" }) { id title publishedAt } } ``` ```graphql mutation UpdateExistingPost { updatePost( id: "1" input: { title: "Updated Title" } ) { id title content } } ``` ```graphql mutation DeletePost { deletePost(id: "1") } ``` -------------------------------- ### GraphQL Yoga Subscription Example Source: https://nitro-graphql.pages.dev/guide/graphql-yoga Implements a subscription for listening to new messages using GraphQL Yoga's pub/sub capabilities. This example sets up a `messageAdded` subscription. ```typescript export const messageSubscriptions = defineSubscription({ messageAdded: { subscribe: (_, __, { pubsub }) => pubsub.asyncIterator(['MESSAGE_ADDED']), }, }) ``` -------------------------------- ### Test GraphQL Queries in Playground Source: https://nitro-graphql.pages.dev/guide/your-first-query Demonstrates how to execute GraphQL queries using the GraphQL Playground interface. Includes examples for fetching all posts and a single post by its ID. ```graphql query GetAllPosts { posts { id title content publishedAt } } ``` ```graphql query GetSinglePost { post(id: "1") { id title content } } ``` -------------------------------- ### Install Dependencies for Federation Subgraph Source: https://nitro-graphql.pages.dev/examples/federation-subgraph Installs necessary packages for creating an Apollo Federation subgraph with nitro-graphql. This includes nitro-graphql, GraphQL, h3, nitropack, and Apollo Federation components. ```bash mkdir users-service cd users-service pnpm init pnpm add nitro-graphql graphql h3 nitropack @apollo/server @apollo/subgraph @as-integrations/h3 ``` -------------------------------- ### Clear Node Modules and Install (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Resets the project's dependencies by removing 'node_modules' and lock files, then performs a fresh installation using pnpm. This resolves 'Cannot find module \'nitro-graphql\' errors. ```bash rm -rf node_modules pnpm-lock.yaml pnpm install ``` -------------------------------- ### Install Prisma and Client for Database Integration Source: https://nitro-graphql.pages.dev/recipes/crud-operations Installs Prisma and its client library, along with Node.js typings, to enable database integration within the project. This is a prerequisite for using Prisma with your database. ```bash pnpm add prisma @prisma/client pnpm add -D @types/node ``` -------------------------------- ### Nitro Configuration (TypeScript) Source: https://nitro-graphql.pages.dev/guide/installation Configures Nitro GraphQL within a Nitro project by adding 'nitro-graphql' to modules and specifying the framework in nitro.config.ts. ```typescript // nitro.config.ts import { defineNitroConfig } from 'nitropack/config' export default defineNitroConfig({ modules: ['nitro-graphql'], graphql: { framework: 'graphql-yoga', // or 'apollo-server' }, }) ``` -------------------------------- ### Clone Nitro GraphQL Repository Source: https://nitro-graphql.pages.dev/contributing/development-setup This command clones the Nitro GraphQL repository from GitHub and navigates into the project directory. Ensure you have Git installed and have forked the repository first. ```bash git clone https://github.com/YOUR_USERNAME/nitro-graphql.git cd nitro-graphql ``` -------------------------------- ### Reinstalling Playground Dependencies Source: https://nitro-graphql.pages.dev/contributing/development-setup This sequence of commands ensures that playground dependencies are correctly installed after a full project build. It involves navigating to the playground directory, removing existing node_modules, and reinstalling using pnpm. ```bash # From the root directory pnpm build # Then reinstall playground dependencies cd playgrounds/nitro rm -rf node_modules pnpm install ``` -------------------------------- ### Nuxt Configuration (TypeScript) Source: https://nitro-graphql.pages.dev/guide/installation Configures Nitro GraphQL for a Nuxt project by adding 'nitro-graphql/nuxt' to modules and specifying the framework within the Nitro configuration in nuxt.config.ts. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nitro-graphql/nuxt'], nitro: { graphql: { framework: 'graphql-yoga', // or 'apollo-server' }, }, }) ``` -------------------------------- ### Activating and Preparing PNPM Version Source: https://nitro-graphql.pages.dev/contributing/development-setup These commands are used to manage the pnpm version, ensuring consistency and resolving potential version mismatches. 'corepack enable' activates Corepack, and 'corepack prepare' installs a specific pnpm version. ```bash corepack enable corepack prepare pnpm@10.18.0 --activate ``` -------------------------------- ### Nuxt Layers File Structure Example Source: https://nitro-graphql.pages.dev/guide/quick-start-nuxt Illustrates the file structure when utilizing Nuxt layers with Nitro GraphQL. It shows how GraphQL schemas and resolvers in a base layer (`layers/base-layer/server/graphql/`) are automatically discovered and merged with the main application's GraphQL schema and resolvers. ```tree your-nuxt-app/ ├── layers/ │ └── base-layer/ │ └── server/ │ └── graphql/ │ ├── schema.graphql # ← Discovered │ └── posts.resolver.ts # ← Discovered └── server/ └── graphql/ ├── schema.graphql # ← Discovered └── users.resolver.ts # ← Discovered ``` -------------------------------- ### Combining Multiple Nitro GraphQL Resolver Files Source: https://nitro-graphql.pages.dev/guide/your-first-query This example illustrates how Nitro GraphQL automatically discovers and merges resolvers defined in separate files. It shows separate files for queries, mutations, and types, emphasizing modularity and organization. ```typescript // server/graphql/posts/queries.resolver.ts export const postQueries = defineQuery({ posts: () => [...], post: () => {...}, }) ``` ```typescript // server/graphql/posts/mutations.resolver.ts export const postMutations = defineMutation({ createPost: () => {...}, updatePost: () => {...}, deletePost: () => {...}, }) ``` ```typescript // server/graphql/posts/types.resolver.ts export const postTypes = defineType({ Post: { author: () => {...}, }, }) ``` -------------------------------- ### Related Examples Source: https://nitro-graphql.pages.dev/examples/federation-subgraph Links to other examples and guides for Nitro GraphQL. ```APIDOC ## Related Examples * [Basic Nitro Server](./nitro-basic.md) - Start here if new to nitro-graphql * [Full-stack Nuxt App](./nuxt-fullstack.md) - Client-side integration * [External Services](./external-services.md) - Integrate third-party APIs ``` -------------------------------- ### Configuration Examples (Code Groups) Source: https://nitro-graphql.pages.dev/contributing/documentation Shows configuration examples for integrating a module (e.g., 'nitro-graphql') into different frameworks (Nitro and Nuxt) using VitePress code groups, allowing users to select the relevant configuration. ```markdown ## Configuration ::: code-group ```typescript [Nitro] // nitro.config.ts export default defineNitroConfig({ modules: ['nitro-graphql'] }) ```` ```typescript [Nuxt] // nuxt.config.ts export default defineNuxtConfig({ modules: ['nitro-graphql'] }) ``` ::: ``` -------------------------------- ### Install Nitro GraphQL Dependencies (Bash) Source: https://nitro-graphql.pages.dev/examples/nitro-basic Commands to create a new Nitro project directory, initialize package.json, and install necessary dependencies including nitro-graphql, graphql, h3, and nitropack. ```bash mkdir my-nitro-app cd my-nitro-app pnpm init pnpm add nitro-graphql graphql h3 nitropack ``` -------------------------------- ### Apollo Gateway Setup (TypeScript) Source: https://nitro-graphql.pages.dev/examples/federation-subgraph Configures and starts an Apollo Gateway in Node.js to compose multiple GraphQL subgraphs. It uses `IntrospectAndCompose` to discover and combine schemas from specified subgraph URLs. The gateway listens on port 4000. ```typescript import { ApolloGateway, IntrospectAndCompose } from '@apollo/gateway' import { ApolloServer } from '@apollo/server' import { startStandaloneServer } from '@apollo/server/standalone' const gateway = new ApolloGateway({ supergraphSdl: new IntrospectAndCompose({ subgraphs: [ { name: 'users', url: 'http://localhost:3000/api/graphql' }, { name: 'posts', url: 'http://localhost:3001/api/graphql' }, // Add more subgraphs as needed ], }), }) const server = new ApolloServer({ gateway, }) const { url } = await startStandaloneServer(server, { listen: { port: 4000 }, }) console.log(`Gateway ready at ${url}`) ``` -------------------------------- ### Traditional vs. Nitro GraphQL Setup (TypeScript) Source: https://nitro-graphql.pages.dev/guide/introduction Compares the manual setup required for a traditional GraphQL integration with the simplified, zero-config approach provided by Nitro GraphQL. The traditional approach involves manual imports and configuration of schema, resolvers, and the server. Nitro GraphQL achieves the same with minimal configuration in nitro.config.ts. ```typescript import { makeExecutableSchema } from '@graphql-tools/schema' import { createYoga } from 'graphql-yoga' import { defineEventHandler } from 'h3' import postResolvers from './resolvers/post' // Import resolvers manually import userResolvers from './resolvers/user' import postSchema from './schemas/post' // Import schemas manually import userSchema from './schemas/user' // Merge everything const schema = makeExecutableSchema({ typeDefs: [userSchema, postSchema], resolvers: [userResolvers, postResolvers] }) // Configure server const yoga = createYoga({ schema }) // Export handler export default defineEventHandler(yoga) ``` ```typescript // nitro.config.ts export default defineNitroConfig({ modules: ['nitro-graphql'], graphql: { framework: 'graphql-yoga' } }) // That's it! Everything else is automatic. ``` -------------------------------- ### Build and Preview VitePress Docs (pnpm) Source: https://nitro-graphql.pages.dev/contributing/documentation Commands to build the static site for VitePress documentation and preview it locally using pnpm. Assumes the user is in the `.docs` directory. ```bash cd .docs pnpm build cd .docs pnpm preview ``` -------------------------------- ### Querying the Supergraph Source: https://nitro-graphql.pages.dev/examples/federation-subgraph Examples of GraphQL queries that span across multiple services (subgraphs) in a federated setup. ```APIDOC ## Querying the Supergraph Once you have the gateway running with both services, you can query across them: ```graphql # Query that spans both services query GetUserWithPosts { user(id: "1") { id name email posts { id title content } } } # Get posts with author details query GetPostsWithAuthors { posts { id title author { id name email } } } ``` ``` -------------------------------- ### Install Drizzle ORM Dependencies Source: https://nitro-graphql.pages.dev/recipes/crud-operations These commands install the necessary Drizzle ORM packages and development tools for your project. ```bash pnpm add drizzle-orm postgres pnpm add -D drizzle-kit ``` -------------------------------- ### Define GraphQL Schema Source: https://nitro-graphql.pages.dev/guide/quick-start-nitro Create a `schema.graphql` file in your `server/graphql/` directory to define your GraphQL schema, including queries and mutations. The module automatically discovers schema files in this directory. ```graphql # server/graphql/schema.graphql type Query { hello: String! greeting(name: String!): String! } type Mutation { _empty: String } ``` -------------------------------- ### Configure package.json for Nitro Dev Server (JSON) Source: https://nitro-graphql.pages.dev/examples/nitro-basic Defines project name, module type, and scripts for running the Nitro development server ('nitro dev'), building the project ('nitro build'), and previewing the built application. Includes core dependencies. ```json { "name": "my-nitro-app", "type": "module", "scripts": { "dev": "nitro dev", "build": "nitro build", "preview": "node .output/server/index.mjs" }, "dependencies": { "graphql": "^16.11.0", "h3": "^2.0.1", "nitro-graphql": "^2.0.0-beta.1", "nitropack": "^3.0.1" } } ``` -------------------------------- ### Install Apollo Server Dependencies for Nitro GraphQL Source: https://nitro-graphql.pages.dev/guide/apollo-server Installs the necessary packages for using Apollo Server with Nitro GraphQL, including the core Apollo libraries and H3 integration. ```bash pnpm add nitro-graphql @apollo/server @apollo/utils.withrequired @as-integrations/h3 graphql ``` -------------------------------- ### Installation Instructions (Code Groups) Source: https://nitro-graphql.pages.dev/contributing/documentation Provides installation instructions for a package using VitePress code groups, offering commands for different package managers like pnpm, npm, and yarn within a single block. ```markdown ## Installation ::: code-group ```bash [pnpm] pnpm add nitro-graphql ```` ```bash [npm] npm install nitro-graphql ``` ```bash [yarn] yarn add nitro-graphql ``` ::: ``` -------------------------------- ### Bash Commands for Running the Nuxt Application Source: https://nitro-graphql.pages.dev/examples/nuxt-fullstack This snippet provides essential bash commands for managing the Nuxt.js application. It covers starting the development server, building the application for production, and previewing the production build. It also lists the default URLs for development and the GraphQL endpoint. ```bash # Development mode pnpm dev # Build for production pnpm build # Preview production build pnpm preview ``` -------------------------------- ### Example GraphQL Create User Mutation Source: https://nitro-graphql.pages.dev/examples/nitro-basic Demonstrates how to execute the `createUser` mutation using GraphQL. It specifies the fields to be returned upon successful creation, including `id`, `name`, `email`, and `createdAt`. This example is useful for testing the `createUser` resolver. ```graphql # Create a new user mutation CreateUser { createUser(input: { name: "Alice Johnson" email: "alice@example.com" }) { id name email createdAt } } ``` -------------------------------- ### Subgraph Deployment Commands (Bash) Source: https://nitro-graphql.pages.dev/examples/federation-subgraph This bash script outlines the steps to build and deploy an individual subgraph service. It uses `pnpm` for package management and indicates that deployment can be done to various platforms, with each subgraph having its own URL. ```bash # Build subgraph pnpm build # Deploy to your platform (Vercel, Netlify, AWS, etc.) # Each subgraph gets its own URL ``` -------------------------------- ### GraphQL Client Queries (GraphQL) Source: https://nitro-graphql.pages.dev/guide/quick-start-nuxt Defines GraphQL queries and mutations for the client-side application. 'GetUsers' fetches a list of users, while 'CreateUser' allows creating a new user with provided input. ```graphql # app/graphql/users/get-users.graphql query GetUsers { users { id name email } } ``` ```graphql # app/graphql/users/create-user.graphql mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id name email } } ``` -------------------------------- ### Troubleshooting Schema Composition Errors Source: https://nitro-graphql.pages.dev/examples/federation-subgraph Common issues and solutions for errors encountered when composing GraphQL schemas in a federated setup. ```APIDOC ## Troubleshooting ### Schema Composition Errors If the gateway can't compose your schemas: * Ensure all `@key` fields exist on the entity * Check for conflicting field definitions * Validate federation directives are correct ``` -------------------------------- ### Run Prisma Migrations and Generate Client Source: https://nitro-graphql.pages.dev/recipes/database-integration Commands to manage database schema migrations and generate the Prisma Client. `prisma migrate dev --name init` creates and applies initial migrations, `prisma generate` updates the client based on the schema, and `prisma studio` opens a GUI for database inspection. ```bash # Create migration npx prisma migrate dev --name init # Generate Prisma Client npx prisma generate # View database in browser npx prisma studio ``` -------------------------------- ### Setup Nitro GraphQL Dependency Source: https://nitro-graphql.pages.dev/contributing/adding-features This snippet shows how to add the nitro-graphql package to your project using pnpm. It's a prerequisite for using the library in your examples or development. ```bash pnpm add nitro-graphql ``` -------------------------------- ### Complete Nitro GraphQL Configuration Example Source: https://nitro-graphql.pages.dev/api/configuration A comprehensive example of Nitro's GraphQL configuration, illustrating settings for framework, endpoints, playground, file generation, client utilities, SDK, types, paths, external services, and code generation, including loader validation. ```typescript export default defineNitroConfig({ graphql: { // Framework selection framework: 'graphql-yoga', // Endpoints endpoint: { graphql: '/api/graphql', healthCheck: '/api/health' }, // Playground playground: process.env.NODE_ENV !== 'production', // File generation control scaffold: { graphqlConfig: true, serverSchema: true, serverConfig: true, serverContext: true }, clientUtils: { index: true, ofetch: true }, sdk: { main: true, external: true }, types: { server: true, client: true, external: true }, // Global paths paths: { serverGraphql: 'server/graphql', clientGraphql: 'app/graphql', typesDir: '.nitro/types' }, // External services externalServices: [ { name: 'github', schema: 'https://api.github.com/graphql', endpoint: 'https://api.github.com/graphql', headers: () => ({ Authorization: `Bearer ${process.env.GITHUB_TOKEN}` }), documents: ['app/graphql/github/**/*.graphql'] } ], // Code generation codegen: { server: { contextType: '~/server/graphql/context#GraphQLContext', scalars: { DateTime: 'Date' } }, client: { scalars: { DateTime: 'string' } } }, // File loader loader: { validate: true } } }) ``` -------------------------------- ### Nitro 'dev:start' Hook for GraphQL Schema Validation Source: https://nitro-graphql.pages.dev/api/hooks This advanced hook example uses 'dev:start' to validate all GraphQL schemas in the 'server/graphql' directory using the 'graphql' library. It scans files, reads their content, builds the schema, and reports success or failure for each file, ensuring schema integrity during development. ```typescript // nitro.config.ts import { buildSchema } from 'graphql' export default defineNitroConfig({ graphql: { framework: 'graphql-yoga' }, hooks: { 'dev:start': async () => { // Validate all GraphQL schemas const schemaFiles = await glob('server/graphql/**/*.graphql') for (const file of schemaFiles) { try { const content = await readFile(file, 'utf-8') buildSchema(content) console.log(`✓ ${file}`) } catch (error) { console.error(`✗ ${file}:`, error.message) } } } } }) ``` -------------------------------- ### Example Nitro Configuration Source: https://nitro-graphql.pages.dev/contributing/documentation A snippet showing the basic Nitro configuration file (`nitro.config.ts`) with the 'nitro-graphql' module included. ```typescript // nitro.config.ts export default defineNitroConfig({ modules: ['nitro-graphql'] }) ``` -------------------------------- ### Nitro 'dev:start' Hook for Watch and Reload Pattern Source: https://nitro-graphql.pages.dev/api/hooks This example implements the 'Watch and Reload Pattern' using the 'dev:start' hook. It utilizes the 'chokidar' library to watch for changes in GraphQL schema files and triggers a regeneration process when a change is detected, ensuring the server stays up-to-date with schema modifications. ```typescript import { watch } from 'chokidar' export default defineNitroConfig({ hooks: { 'dev:start': () => { const watcher = watch('server/graphql/**/*.graphql') watcher.on('change', async (path) => { console.log('Schema changed:', path) // Trigger type regeneration }) } } }) ``` -------------------------------- ### GraphQL Schema with Custom Directives Source: https://nitro-graphql.pages.dev/guide/custom-directives Example of a GraphQL schema utilizing custom directives for features like authentication and caching. Directives are denoted by '@' followed by the directive name. ```graphql type Query { profile: User @auth adminData: String @auth(requires: "ADMIN") expensiveData: String @cache(ttl: 300) } ``` -------------------------------- ### Virtual Imports in TypeScript Source: https://nitro-graphql.pages.dev/guide/auto-discovery Shows examples of virtual imports used internally by the Nitro GraphQL server for directives, resolvers, and schemas. These are for internal use and should not be used directly. ```ts import directives from '#nitro-internal-virtual/server-directives' import resolvers from '#nitro-internal-virtual/server-resolvers' // Virtual import - DO NOT use directly import schemas from '#nitro-internal-virtual/server-schemas' ``` -------------------------------- ### Configure Nitro for GraphQL Source: https://nitro-graphql.pages.dev/guide/quick-start-nitro Add `nitro-graphql` to your Nitro modules and specify `graphql-yoga` as the framework in your `nitro.config.ts` file. This enables the GraphQL module within your Nitro project. ```typescript import { defineNitroConfig } from 'nitropack/config' export default defineNitroConfig({ modules: ['nitro-graphql'], graphql: { framework: 'graphql-yoga', }, }) ``` -------------------------------- ### GraphQL Schema: Non-Nullable Fields (GraphQL) Source: https://nitro-graphql.pages.dev/guide/schemas Example highlighting the importance of making fields non-nullable when their presence is a requirement. This improves data integrity and clarity on expected values. ```graphql # ✅ Good - Clear requirements type User { id: ID! name: String! email: String! bio: String # Nullable - actually optional } # ❌ Bad - Everything nullable type User { id: ID name: String email: String } ``` -------------------------------- ### Initialize Prisma Project Source: https://nitro-graphql.pages.dev/recipes/crud-operations Initializes a new Prisma project in the current directory. This command generates the necessary configuration files and directory structure for Prisma to manage your database schema. ```bash npx prisma init ``` -------------------------------- ### Nitro GraphQL File Organization Example Source: https://nitro-graphql.pages.dev/contributing/adding-features Illustrates the recommended directory structure for placing new code within the Nitro GraphQL project, such as types, utilities, routes, and ecosystem integrations. ```bash src/ ├── index.ts # Add module setup code here ├── types/ │ └── index.ts # Add new type definitions ├── utils/ │ └── your-util.ts # Add utility functions ├── routes/ │ └── your-route.ts # Add new route handlers └── ecosystem/ └── your-integration.ts # Add framework integrations ``` -------------------------------- ### Delete Build Directories (Bash) Source: https://nitro-graphql.pages.dev/guide/installation Removes the build cache directories for Nitro or Nuxt to force a regeneration of necessary files, often resolving TypeScript type generation problems. ```bash # Nitro rm -rf .nitro # Nuxt rm -rf .nuxt ``` -------------------------------- ### Resolver Scanning Example in TypeScript Source: https://nitro-graphql.pages.dev/guide/auto-discovery Illustrates how Nitro GraphQL scans for exported functions using `defineQuery`, `defineMutation`, etc., to discover resolvers. Non-`define*` functions are not discovered. ```ts // server/graphql/users.resolver.ts export const userQueries = defineQuery({ users: () => [], // ← Discovered }) export const userMutations = defineMutation({ createUser: () => ({}), // ← Discovered }) // This won't be discovered (not using a define function) export function someHelper() {} ```