### Install Pothos GraphQL with npm Source: https://pothos-graphql.dev/docs/guide Installs the core Pothos library and graphql-yoga for server implementation. This is the first step to using Pothos in your project. ```bash npm install --save @pothos/core graphql-yoga ``` -------------------------------- ### Create a Simple GraphQL Schema with Pothos Source: https://pothos-graphql.dev/docs/guide Defines a basic GraphQL schema using Pothos, including a 'hello' query that accepts a 'name' argument. This demonstrates how to build queries and define arguments. ```typescript import SchemaBuilder from '@pothos/core'; const builder = new SchemaBuilder({}); builder.queryType({ fields: (t) => ({ hello: t.string({ args: { name: t.arg.string(), }, resolve: (parent, { name }) => `hello, ${name || 'World'}`, }), }), }); const schema = builder.toSchema(); ``` -------------------------------- ### Create a GraphQL Server with Pothos and graphql-yoga Source: https://pothos-graphql.dev/docs/guide Sets up a Node.js HTTP server using graphql-yoga and the Pothos-generated schema. This allows your GraphQL API to be accessible over the network. ```typescript import { createYoga } from 'graphql-yoga'; import { createServer } from 'node:http'; const yoga = createYoga({ schema: builder.toSchema(), }); const server = createServer(yoga); server.listen(3000); ``` -------------------------------- ### Install Pothos Prisma Plugin (npm) Source: https://pothos-graphql.dev/docs/plugins/prisma/setup Installs the Pothos Prisma plugin using npm. This is the first step to integrating Prisma with Pothos GraphQL. ```bash npm install --save @pothos/plugin-prisma ``` -------------------------------- ### Create GraphQL Server with graphql-yoga Source: https://pothos-graphql.dev/docs/guide/objects Sets up a basic GraphQL server using graphql-yoga and the Pothos schema builder. Includes basic context setup. ```typescript import { createServer } from 'http'; import { createYoga } from 'graphql-yoga'; const yoga = createYoga({ schema: builder.toSchema(), context: (ctx) => ({ user: { id: Number.parseInt(ctx.request.headers.get('x-user-id') ?? '1', 10) }, }), }); export const server = createServer(yoga); server.listen(3000); ``` -------------------------------- ### Prisma Schema with Pothos Generator Options Source: https://pothos-graphql.dev/docs/plugins/prisma/setup Example of a prisma schema including both the 'client' and 'pothos' generators with custom output paths. ```prisma generator client { provider = "prisma-client" output = "../lib/prisma" } generator pothos { provider = "prisma-pothos-types" clientOutput = "./prisma" // relative path from pothos output to prisma client output = "../lib/pothos-prisma-types.ts" } ``` -------------------------------- ### TypeScript Configuration for Pothos Source: https://pothos-graphql.dev/docs/guide Ensures type safety by enabling strict mode in your tsconfig.json. Pothos relies on strict TypeScript settings to provide its type-safe features. ```json { "compilerOptions": { "strict": true } } ``` -------------------------------- ### Install Pothos Mocks Plugin (npm) Source: https://pothos-graphql.dev/docs/plugins/mocks Installs the Pothos Mocks plugin using npm. This is the first step to using the plugin in your project. ```bash npm install --save @pothos/plugin-mocks ``` -------------------------------- ### Basic Pothos New Relic Tracing Setup (TypeScript) Source: https://pothos-graphql.dev/docs/plugins/tracing This example shows the basic setup for using the Pothos tracing plugin with New Relic. It creates a New Relic wrapper for resolvers and configures the SchemaBuilder to use the tracing plugin, applying the New Relic wrapper to root fields. ```typescript import SchemaBuilder from '@pothos/core'; import TracingPlugin, { isRootField } from '@pothos/plugin-tracing'; import { createNewrelicWrapper } from '@pothos/tracing-newrelic'; const wrapResolver = createNewrelicWrapper({ includeArgs: true, includeSource: true, }); export const builder = new SchemaBuilder({ plugins: [TracingPlugin], tracing: { default: (config) => isRootField(config), wrap: (resolver) => wrapResolver(resolver), }, }); ``` -------------------------------- ### Setup Basic OpenTelemetry Tracer with Console Exporter Source: https://pothos-graphql.dev/docs/plugins/tracing This code sets up a basic OpenTelemetry tracer using `NodeTracerProvider` and logs spans to the console via `ConsoleSpanExporter`. It also registers HTTP instrumentation to automatically create spans for outgoing HTTP requests. This is a foundational setup for tracing. Ensure `@opentelemetry/api`, `@opentelemetry/instrumentation`, `@opentelemetry/instrumentation-http`, and `@opentelemetry/sdk-trace-base`, `@opentelemetry/sdk-trace-node` are installed. ```typescript import { diag, DiagConsoleLogger, DiagLogLevel, trace } from '@opentelemetry/api'; import { registerInstrumentations } from '@opentelemetry/instrumentation'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; export const provider = new NodeTracerProvider({ spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())] }); provider.register(); registerInstrumentations({ // Automatically create spans for http requests instrumentations: [new HttpInstrumentation({})], }); diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO); export const tracer = trace.getTracer('graphql'); ``` -------------------------------- ### Create Yoga Server with Context Initialization (TypeScript) Source: https://pothos-graphql.dev/docs/guide/context Sets up a Pothos GraphQL server using createYoga, defining the schema and providing a context function that asynchronously fetches user data from the authorization header to populate the currentUser. It then starts the server. ```typescript const yoga = createYoga({ schema, context: async ({ req }) => ({ // This part is up to you! currentUser: await getUserFromAuthHeader(req.headers.authorization), }), }); const server = createServer(yoga); server.listen(3000); ``` -------------------------------- ### Install With-Input Plugin Source: https://pothos-graphql.dev/docs/plugins/with-input Installs the With-Input plugin for Pothos GraphQL using npm. This is the first step to enable the plugin's functionality. ```bash npm install --save @pothos/plugin-with-input ``` -------------------------------- ### Pothos Zod Validation Plugin Setup Source: https://pothos-graphql.dev/docs/plugins/zod Demonstrates how to install the Zod plugin and set up the Pothos schema builder with basic Zod validation configuration. ```APIDOC ## Install ```bash npm install --save zod @pothos/plugin-zod ``` ## Setup ```javascript import ZodPlugin from '@pothos/plugin-zod'; import SchemaBuilder from '@pothos/core'; const builder = new SchemaBuilder({ plugins: [ZodPlugin], zod: { // optionally customize how errors are formatted validationError: (zodError, args, context, info) => { // the default behavior is to just throw the zod error directly return zodError; }, }, }); builder.queryType({ fields: (t) => ({ simple: t.boolean({ args: { // Validate individual args email: t.arg.string({ validate: { email: true, }, }), phone: t.arg.string(), }, // Validate all args together validate: (args) => !!args.phone || !!args.email, resolve: () => true, }), }), }); ``` ``` -------------------------------- ### Install and Setup Pothos SubGraph Plugin Source: https://pothos-graphql.dev/docs/plugins/sub-graph Installs the SubGraph plugin using npm and demonstrates basic setup with SchemaBuilder. It shows how to create default and subgraph-specific schemas, including combined and intersection schemas. ```bash npm install --save @pothos/plugin-sub-graph ``` ```typescript import SubGraphPlugin from '@pothos/plugin-sub-graph'; const builder = new SchemaBuilder({ plugins: [SubGraphPlugin], subGraphs: { defaultForTypes: [], fieldsInheritFromTypes: true, }, }); //in another file: const schema = builder.toSchema(); const publicSchema = builder.toSchema({ subGraph: 'Public' }); const internalSchema = builder.toSchema({ subGraph: 'Internal' }); // You can also build a graph containing multiple subgraphs: const combinedSchema = builder.toSchema({ subGraph: ['Internal', 'Public'] }); // Or create a graph of the intersection between multiple subgraphs: const allSchema = builder.toSchema({ subGraph: { all: ['Internal', 'Public'] } }); ``` -------------------------------- ### Install Smart Subscriptions Plugin (npm) Source: https://pothos-graphql.dev/docs/plugins/smart-subscriptions Command to install the Pothos Smart Subscriptions plugin using npm. This is the first step in integrating the plugin into your project. ```bash npm install --save @pothos/plugin-smart-subscriptions ``` -------------------------------- ### Basic Pothos Sentry Tracing Setup (TypeScript) Source: https://pothos-graphql.dev/docs/plugins/tracing This example demonstrates the basic configuration for using the Pothos tracing plugin with Sentry. It creates a Sentry wrapper for resolvers and configures the SchemaBuilder to apply this wrapper to root fields, enabling Sentry performance monitoring. ```typescript import SchemaBuilder from '@pothos/core'; import TracingPlugin, { isRootField } from '@pothos/plugin-tracing'; import { createSentryWrapper } from '@pothos/tracing-sentry'; const traceResolver = createSentryWrapper({ includeArgs: true, includeSource: true, }); export const builder = new SchemaBuilder({ plugins: [TracingPlugin], tracing: { default: (config) => isRootField(config), wrap: (resolver, options) => traceResolver(resolver, options), }, }); ``` -------------------------------- ### Defining List Fields Source: https://pothos-graphql.dev/docs/guide/fields This example demonstrates how to define fields that return lists of objects or lists of scalars by wrapping the type in an array. ```APIDOC ## POST /graphql ### Description Defines fields that return lists of 'Giraffe' objects and lists of Strings. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "query": "{ giraffes { name } giraffeNames }" } ``` ### Response #### Success Response (200) - **giraffes** (Giraffe[]) - A list of giraffes. - **name** (String) - The name of the giraffe. - **giraffeNames** (String[]) - A list of giraffe names. #### Response Example ```json { "data": { "giraffes": [ { "name": "Gina" }, { "name": "James" } ], "giraffeNames": ["Gina", "James"] } } ``` ``` -------------------------------- ### Installing graphql-code-generator CLI and TypeScript Source: https://pothos-graphql.dev/docs/guide/generating-client-types This command installs the necessary packages for using graphql-code-generator with TypeScript. It includes the core graphql package, the CLI, and a client preset for generating types. ```bash npm install --save graphql npm install --save -D typescript @graphql-codegen/cli @graphql-codegen/client-preset ``` -------------------------------- ### Install Pothos Complexity Plugin Source: https://pothos-graphql.dev/docs/plugins/complexity Installs the Pothos Complexity plugin using npm. This is the first step to enable complexity management in your GraphQL schema. ```bash npm install --save @pothos/plugin-complexity ``` -------------------------------- ### Install OpenTelemetry Tracing Plugin for Pothos GraphQL Source: https://pothos-graphql.dev/docs/plugins/tracing Provides the npm, pnpm, yarn, and bun commands to install the `@pothos/tracing-opentelemetry` package along with necessary OpenTelemetry dependencies. ```bash npm install --save @pothos/tracing-opentelemetry @opentelemetry/semantic-conventions @opentelemetry/api ``` -------------------------------- ### Exposing Fields from Underlying Data Source: https://pothos-graphql.dev/docs/guide/fields This example demonstrates how to use helper methods like `exposeString` to easily expose fields from the underlying data object for non-root types. ```APIDOC ## POST /graphql ### Description Defines the 'name' field for the 'Giraffe' object type using the `exposeString` helper. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "query": "{ giraffe { name } }" } ``` ### Response #### Success Response (200) - **giraffe** (Giraffe) - An object representing a giraffe. - **name** (String) - The name of the giraffe, exposed from the underlying data. #### Response Example ```json { "data": { "giraffe": { "name": "Gina" } } } ``` ``` -------------------------------- ### Installing schema-ast Plugin for graphql-code-generator Source: https://pothos-graphql.dev/docs/guide/generating-client-types This command installs the `@graphql-codegen/schema-ast` plugin, which allows graphql-code-generator to output your schema in SDL format to a `.graphql` file. ```bash npm install --save -D @graphql-codegen/schema-ast ``` -------------------------------- ### Initialize Pothos with Drizzle, Relay, and WithInput Plugins Source: https://pothos-graphql.dev/docs/plugins/drizzle Initializes the Pothos SchemaBuilder with Drizzle, Relay, and WithInput plugins. This configuration is common for examples and assumes these plugins are installed. ```typescript import { drizzle } from 'drizzle-orm/...'; import SchemaBuilder from '@pothos/core'; import DrizzlePlugin from '@pothos/plugin-drizzle'; import RelayPlugin from '@pothos/plugin-relay'; import WithInputPlugin from '@pothos/plugin-with-input'; import { getTableConfig } from 'drizzle-orm/sqlite-core'; import { relations } from './db/relations'; const db = drizzle(client, { relations }); export interface PothosTypes { DrizzleRelations: typeof relations; } const builder = new SchemaBuilder({ plugins: [RelayPlugin, WithInputPlugin, DrizzlePlugin], drizzle: { client: db, getTableConfig, relations, }, }); ``` -------------------------------- ### Install Pothos Tracing Plugin (npm) Source: https://pothos-graphql.dev/docs/plugins/tracing Installs the Pothos Tracing plugin using npm. This is the first step to integrating tracing capabilities into your Pothos GraphQL schema. ```bash npm install --save @pothos/plugin-tracing ``` -------------------------------- ### Setup Pothos GraphQL Schema with Validation Plugin Source: https://pothos-graphql.dev/docs/plugins/validation Example of setting up a Pothos GraphQL schema builder with the ValidationPlugin and defining a query with a validated email argument using Zod. ```typescript import ValidationPlugin from '@pothos/plugin-validation'; import { z } from 'zod'; // or your preferred validation library const builder = new SchemaBuilder({ plugins: [ValidationPlugin], }); builder.queryType({ fields: (t) => ({ simple: t.boolean({ args: { // Validate individual arguments email: t.arg.string({ validate: z.string().email(), }), }, resolve: () => true, }), }), }); ``` -------------------------------- ### Install AWS X-Ray for Pothos Tracing Source: https://pothos-graphql.dev/docs/plugins/tracing Installs the necessary packages for integrating AWS X-Ray tracing with Pothos GraphQL. Requires `npm`, `pnpm`, `yarn`, or `bun`. ```bash npm install --save @pothos/tracing-xray aws-xray-sdk-core ``` -------------------------------- ### Install Relay Plugin with npm Source: https://pothos-graphql.dev/docs/plugins/relay This snippet shows the command to install the Relay plugin using npm. This is a prerequisite for using the plugin in your project. ```bash npm install --save @pothos/plugin-relay ``` -------------------------------- ### Generate Prisma Client and Pothos Types Source: https://pothos-graphql.dev/docs/plugins/prisma/setup Command to re-generate the Prisma client and create the Pothos-specific types based on your prisma schema. ```bash npx prisma generate ``` -------------------------------- ### Install @pothos/plugin-add-graphql Source: https://pothos-graphql.dev/docs/plugins/add-graphql Command to install the Add GraphQL plugin using npm. This is the first step to integrating existing GraphQL schemas with Pothos. ```bash npm install --save @pothos/plugin-add-graphql ``` -------------------------------- ### Install Apollo Server Dependency Source: https://pothos-graphql.dev/docs/plugins/federation Installs the Apollo Server package, which is often used with Pothos for serving GraphQL APIs. While not strictly required if using a different server, it's commonly installed. ```bash npm install --save @apollo/server ``` -------------------------------- ### Install @pothos/plugin-grafast and grafast Source: https://pothos-graphql.dev/docs/plugins/grafast Installs the Grafast plugin for Pothos and the grafast package itself using npm. Ensure grafast version is compatible. ```bash npm install --save @pothos/plugin-grafast grafast@>=0.1.1-beta.24 ``` -------------------------------- ### Setup Pothos with Smart Subscriptions Plugin Source: https://pothos-graphql.dev/docs/plugins/smart-subscriptions Basic setup for Pothos SchemaBuilder to include the Smart Subscriptions plugin. It shows the essential configuration options for subscriptions, including debounce delay, subscribe, and unsubscribe functions. ```typescript import SchemaBuilder from '@pothos/core'; import SmartSubscriptionsPlugin from '@pothos/plugin-smart-subscriptions'; const builder = new SchemaBuilder({ plugins: [SmartSubscriptionsPlugin], smartSubscriptions: { debounceDelay: number | null; subscribe: (name: string, context: Context, cb: (err: unknown, data?: unknown) => void) => Promise | void; unsubscribe: (name: string, context: Context) => Promise | void; }, }); ``` -------------------------------- ### Install Pothos Validation Plugin with Zod, Valibot, or ArkType Source: https://pothos-graphql.dev/docs/plugins/validation Instructions for installing the Pothos Validation plugin along with a compatible validation library such as Zod, Valibot, or ArkType using npm. ```bash npm install --save @pothos/plugin-validation zod # OR npm install --save @pothos/plugin-validation valibot # OR npm install --save @pothos/plugin-validation arktype ``` -------------------------------- ### Install Pothos Directive Plugin Source: https://pothos-graphql.dev/docs/plugins/directives Install the Pothos Directive plugin using npm. This command adds the necessary package to your project's dependencies. ```bash npm install --save @pothos/plugin-directives ``` -------------------------------- ### Defining Scalar Fields using Convenience Methods Source: https://pothos-graphql.dev/docs/guide/fields This example shows the use of convenience methods for defining common scalar fields like ID, Int, Float, Boolean, and String, along with their list counterparts. ```APIDOC ## POST /graphql ### Description Defines various scalar fields for the Query type using convenience methods. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "query": "{ id int float boolean string idList intList floatList booleanList stringList }" } ``` ### Response #### Success Response (200) - **id** (ID) - The ID field. - **int** (Int) - The Int field. - **float** (Float) - The Float field. - **boolean** (Boolean) - The Boolean field. - **string** (String) - The String field. - **idList** (ID[]) - The list of IDs. - **intList** (Int[]) - The list of Ints. - **floatList** (Float[]) - The list of Floats. - **booleanList** (Boolean[]) - The list of Booleans. - **stringList** (String[]) - The list of Strings. #### Response Example ```json { "data": { "id": "123", "int": 123, "float": 1.23, "boolean": false, "string": "abc", "idList": ["123"], "intList": [123], "floatList": [1.23], "booleanList": [false], "stringList": ["abc"] } } ``` ``` -------------------------------- ### Configure Pothos Builder with Prisma Plugin Source: https://pothos-graphql.dev/docs/plugins/prisma/setup Sets up the Pothos SchemaBuilder with the Prisma plugin, including the Prisma client and datamodel information. ```typescript import SchemaBuilder from '@pothos/core'; import { PrismaClient } from '@prisma/client'; import PrismaPlugin from '@pothos/plugin-prisma'; import type PrismaTypes from '../lib/pothos-prisma-types'; // path to generated types, specified in your prisma.schema import { getDatamodel } from '../lib/pothos-prisma-types'; const prisma = new PrismaClient({}); const builder = new SchemaBuilder<{ PrismaTypes: PrismaTypes; }>({ plugins: [PrismaPlugin], prisma: { client: prisma, dmmf: getDatamodel(), exposeDescriptions: boolean | { models: boolean, fields: boolean }, filterConnectionTotalCount: true, onUnusedQuery: process.env.NODE_ENV === 'production' ? null : 'warn', }, }); ``` -------------------------------- ### Install Pothos Zod Plugin Source: https://pothos-graphql.dev/docs/plugins/zod Installs the necessary Zod package and the Pothos Zod plugin using npm. Ensure you have Node.js and npm installed. ```bash npm install --save zod @pothos/plugin-zod ``` -------------------------------- ### Install Simple Objects Plugin (npm) Source: https://pothos-graphql.dev/docs/plugins/simple-objects Installs the Simple Objects Plugin using npm. This is the first step to enable its functionality in your Pothos GraphQL schema. ```bash npm install --save @pothos/plugin-simple-objects ``` -------------------------------- ### Install Pothos Drizzle Plugin Source: https://pothos-graphql.dev/docs/plugins/drizzle Installs the Pothos Drizzle plugin and Drizzle ORM with the beta tag. This package requires Drizzle ORM v2 API and may have breaking changes. ```bash npm install --save @pothos/plugin-drizzle drizzle-orm@beta ``` -------------------------------- ### Build Subgraph Schema and Start Apollo Server Source: https://pothos-graphql.dev/docs/plugins/federation Shows how to create a subgraph schema using Pothos GraphQL's `toSubGraphSchema` method, specifying the link URL for federation specifications and listing federation directives. It then initializes an ApolloServer with the schema and starts it as a standalone server, logging the URL. ```typescript // Use new `toSubGraphSchema` method to add subGraph specific types and queries to the schema const schema = builder.toSubGraphSchema({ // defaults to v2.6 linkUrl: 'https://specs.apollo.dev/federation/v2.3', // defaults to the list of directives used in your schema federationDirectives: ['@key', '@external', '@requires', '@provides'], }); const server = new ApolloServer({ schema, }); startStandaloneServer(server, { listen: { port: 4000 } }) .then(({ url }) => { console.log(`🚀 Server ready at ${url}`); }) .catch((error) => { throw error; }); ``` -------------------------------- ### Basic Prisma Object Type Setup with Pothos Source: https://pothos-graphql.dev/docs/plugins/prisma/without-a-plugin Demonstrates how to define GraphQL object types (User, Post) backed by Prisma models. It shows basic field exposure and setting up relationships with nested queries. This setup is straightforward but can lead to N+1 query issues if not optimized. ```typescript import { Post, PrismaClient, User } from '@prisma/client'; const db = new PrismaClient(); const UserObject = builder.objectRef('User'); const PostObject = builder.objectRef('Post'); UserObject.implement({ fields: (t) => ({ id: t.exposeID('id'), email: t.exposeString('email'), posts: t.field({ type: [PostObject], resolve: (user) => db.post.findMany({ where: { authorId: user.id }, }), }), }), }); PostObject.implement({ fields: (t) => ({ id: t.exposeID('id'), title: t.exposeString('title'), author: t.field({ type: UserObject, resolve: (post) => db.user.findUniqueOrThrow({ where: { id: post.authorId } }), }), }), }); builder.queryType({ fields: (t) => ({ me: t.field({ type: UserObject, resolve: (root, args, ctx) => db.user.findUniqueOrThrow({ where: { id: ctx.userId } }), }), }), }); ``` -------------------------------- ### Install Pothos Tracing Plugin for Sentry (npm) Source: https://pothos-graphql.dev/docs/plugins/tracing Install the necessary packages for integrating Pothos GraphQL tracing with Sentry using npm. This command adds the Pothos Sentry tracing adapter and the Sentry Node.js SDK to your project dependencies. ```bash npm install --save @pothos/tracing-sentry @sentry/node ``` -------------------------------- ### Install Federation Plugin Dependencies Source: https://pothos-graphql.dev/docs/plugins/federation Installs the Pothos Federation plugin, the Directives plugin, and the Apollo subgraph package using npm. This is a prerequisite for using federation features with Pothos. ```bash npm install --save @pothos/plugin-federation @pothos/plugin-directives @apollo/subgraph ``` -------------------------------- ### Setup Pothos Builder with Add GraphQL Plugin Source: https://pothos-graphql.dev/docs/plugins/add-graphql Basic setup for the Pothos SchemaBuilder, including the AddGraphQLPlugin. This initializes the builder with the necessary plugin for adding external GraphQL types. ```typescript import AddGraphQLPlugin from '@pothos/plugin-add-graphql'; const builder = new SchemaBuilder({ plugins: [AddGraphQLPlugin], }); ``` -------------------------------- ### Basic Plugin Setup with SchemaBuilder Source: https://pothos-graphql.dev/docs/guide/using-plugins Demonstrates how to import and configure the ScopeAuthPlugin when initializing a Pothos SchemaBuilder. This sets up the builder to use the features provided by the plugin. ```typescript import SchemaBuilder from '@pothos/core'; import ScopeAuthPlugin from '@pothos/plugin-scope-auth'; const builder = new SchemaBuilder({ plugins: [ScopeAuthPlugin], }); ``` -------------------------------- ### Install Scope Auth Plugin with npm Source: https://pothos-graphql.dev/docs/guide/using-plugins Installs the @pothos/plugin-scope-auth package using npm. This is the first step to using the scope-auth plugin in your Pothos GraphQL schema. ```bash npm install --save @pothos/plugin-scope-auth ``` -------------------------------- ### Install Pothos Tracing Plugin for New Relic (npm) Source: https://pothos-graphql.dev/docs/plugins/tracing Install the necessary packages for integrating Pothos GraphQL tracing with New Relic using npm. This command adds the Pothos New Relic tracing adapter and the New Relic Node.js agent to your project dependencies. ```bash npm install --save @pothos/tracing-newrelic newrelic @types/newrelic ``` -------------------------------- ### Setup GrafastPlugin with SchemaBuilder Source: https://pothos-graphql.dev/docs/plugins/grafast Sets up the Pothos SchemaBuilder to use the GrafastPlugin. This involves importing the plugin and configuring BuilderTypes to expect Grafast plans. ```typescript import GrafastPlugin from '@pothos/plugin-grafast'; declare global { namespace Grafast { // Define the Context type used by grafast interface Context extends YourContextType {} } } type BuilderTypes = { // This tells the builder to expect plans instead of resolvers InferredFieldOptionsKind: 'Grafast'; Context: YourContextType; }; const builder = new SchemaBuilder({ plugins: [GrafastPlugin], }); ``` -------------------------------- ### Hello, World GraphQL API with Pothos and Yoga Source: https://pothos-graphql.dev/docs/index A basic 'Hello, World' GraphQL API example using Pothos for schema building and GraphQL Yoga for the server. It demonstrates defining a query with an argument and setting up an HTTP server. Dependencies include '@pothos/core' and 'graphql-yoga'. ```typescript import { createYoga } from 'graphql-yoga'; import { createServer } from 'node:http'; import SchemaBuilder from '@pothos/core'; const builder = new SchemaBuilder({}); builder.queryType({ fields: (t) => ({ hello: t.string({ args: { name: t.arg.string(), }, resolve: (parent, { name }) => `hello, ${name || 'World'}`, }), }), }); const yoga = createYoga({ schema: builder.toSchema(), }); const server = createServer(yoga); server.listen(3000, () => { console.log('Visit http://localhost:3000/graphql'); }); ``` -------------------------------- ### Example GraphQL Query Source: https://pothos-graphql.dev/docs/guide/objects An example GraphQL query to retrieve data for the 'giraffe' field, requesting its name, age, and height. ```graphql query { giraffe { name age height } } ``` -------------------------------- ### Setup and Example Usage of Pothos Errors Plugin Source: https://pothos-graphql.dev/docs/plugins/errors Demonstrates setting up the Pothos Errors plugin with a SchemaBuilder and defining a query field that can return errors. Requires '@pothos/plugin-errors'. The example shows how to define custom error types and integrate them into schema fields. ```typescript import ErrorsPlugin from '@pothos/plugin-errors'; const builder = new SchemaBuilder({ plugins: [ErrorsPlugin], errors: { defaultTypes: [], // onResolvedError: (error) => console.error('Handled error:', error), }, }); builder.objectType(Error, { name: 'Error', fields: (t) => ({ message: t.exposeString('message'), }), }); builder.queryType({ fields: (t) => ({ hello: t.string({ errors: { types: [Error], }, args: { name: t.arg.string({ required: false }), }, resolve: (parent, { name }) => { if (name.slice(0, 1) !== name.slice(0, 1).toUpperCase()) { throw new Error('name must be capitalized'); } return `hello, ${name || 'World'}`; }, }), }), }); ``` -------------------------------- ### Defining Non-Scalar Object Fields Source: https://pothos-graphql.dev/docs/guide/fields This example illustrates how to define a field that returns an object type, referencing the object by its name defined in SchemaBuilder. ```APIDOC ## POST /graphql ### Description Defines a field 'giraffe' that returns an object of type 'Giraffe'. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "query": "{ giraffe { name } }" } ``` ### Response #### Success Response (200) - **giraffe** (Giraffe) - An object representing a giraffe. #### Response Example ```json { "data": { "giraffe": { "name": "Gina" } } } ``` ``` -------------------------------- ### Setup With-Input Plugin Source: https://pothos-graphql.dev/docs/plugins/with-input Sets up the Pothos GraphQL schema builder with the With-Input plugin. This involves importing the plugin and adding it to the builder's plugins array. Optional configuration for type and argument options can also be provided. ```javascript import WithInputPlugin from '@pothos/plugin-with-input'; const builder = new SchemaBuilder({ plugins: [WithInputPlugin], // optional withInput: { typeOptions: { // default options for Input object types created by this plugin }, argOptions: { // set required: false to override default behavior }, }, }); ``` -------------------------------- ### Defining Fields with Enums and Refs Source: https://pothos-graphql.dev/docs/guide/fields This example shows how to define fields that use Enums and how to reference types not directly described in SchemaTypes using a Ref. ```APIDOC ## POST /graphql ### Description Defines an enum 'LengthUnit' and uses it for a field within the 'Giraffe' object type. Also defines a query field 'giraffe' that returns a 'Giraffe' object. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "query": "{ giraffe { preferredNeckLengthUnit } }" } ``` ### Response #### Success Response (200) - **giraffe** (Giraffe) - An object representing a giraffe. - **preferredNeckLengthUnit** (LengthUnit) - The preferred neck length unit for the giraffe. #### Response Example ```json { "data": { "giraffe": { "preferredNeckLengthUnit": "Feet" } } } ``` ``` -------------------------------- ### Pothos Schema Builder Setup with Prisma Plugins Source: https://pothos-graphql.dev/docs/plugins/prisma/prisma-utils Set up your Pothos SchemaBuilder by importing necessary modules, initializing PrismaClient, and including both the PrismaPlugin and PrismaUtils in the plugins array. The prisma configuration includes the client instance and the datamodel obtained from getDatamodel(). ```typescript import SchemaBuilder from '@pothos/core'; import { PrismaClient } from '@prisma/client'; import type PrismaTypes from '../lib/pothos-prisma-types'; import { getDatamodel } from '../lib/pothos-prisma-types'; import PrismaPlugin from '@pothos/plugin-prisma'; import PrismaUtils from '@pothos/plugin-prisma-utils'; export const prisma = new PrismaClient({}); export default new SchemaBuilder<{ Scalars: { DateTime: { Input: Date; Output: Date; }; }; PrismaTypes: PrismaTypes; }>({ plugins: [PrismaPlugin, PrismaUtils], prisma: { client: prisma, dmmf: getDatamodel(), }, }); ``` -------------------------------- ### Basic Pothos Tracing Plugin Setup Source: https://pothos-graphql.dev/docs/plugins/tracing Sets up the Pothos Tracing plugin with default configurations. It enables tracing for root fields and logs resolver execution duration. ```typescript import TracingPlugin, { wrapResolver, isRootField } from '@pothos/plugin-tracing'; const builder = new SchemaBuilder({ plugins: [TracingPlugin], tracing: { // Enable tracing for rootFields by default, other fields need to opt in default: (config) => isRootField(config), // Log resolver execution duration wrap: (resolver, options, config) => wrapResolver(resolver, (error, duration) => { console.log(`Executed resolver ${config.parentType}.${config.name} in ${duration}ms`); }), }, }); ``` -------------------------------- ### Defining Non-Nullable Fields Source: https://pothos-graphql.dev/docs/guide/fields This example illustrates how to make fields, list items, or entire lists non-nullable by setting the `nullable` option to `false` or an object specifying nullability for list and items. ```APIDOC ## POST /graphql ### Description Defines fields with different nullability constraints: a non-nullable string field, a non-nullable list, and a list with nullable items. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "query": "{ nonNullableField nonNullableString nonNullableList sparseList }" } ``` ### Response #### Success Response (200) - **nonNullableField** (String!) - A non-nullable string field. - **nonNullableString** (String!) - A non-nullable string field using a convenience method. - **nonNullableList** (String![]) - A non-nullable list of strings. - **sparseList** (String[]) - A list of nullable strings. #### Response Example ```json { "data": { "nonNullableField": null, "nonNullableString": null, "nonNullableList": null, "sparseList": [null] } } ``` ``` -------------------------------- ### Defining Scalar Fields using 'field' method Source: https://pothos-graphql.dev/docs/guide/fields This example demonstrates how to define a scalar field named 'name' for the Query type using the `field` method, specifying its type and a resolve function. ```APIDOC ## POST /graphql ### Description Defines a scalar field named 'name' for the Query type. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "query": "{ name }" } ``` ### Response #### Success Response (200) - **name** (String) - The name field. #### Response Example ```json { "data": { "name": "Gina" } } ``` ``` -------------------------------- ### Define Animal and Giraffe Classes for Interfaces Source: https://pothos-graphql.dev/docs/guide/interfaces Defines example TypeScript classes `Animal` and `Giraffe`, along with a `Diet` enum, to be used for demonstrating GraphQL interface implementation. This setup is optional; only the schema definition matters. ```typescript export class Animal { diet: Diet; constructor(diet: Diet) { this.diet = diet; } } export class Giraffe extends Animal { name: string; birthday: Date; heightInMeters: number; constructor(name: string, birthday: Date, heightInMeters: number) { super(Diet.HERBIVOROUS); this.name = name; this.birthday = birthday; this.heightInMeters = heightInMeters; } } export enum Diet { HERBIVOROUS, CARNIVOROUS, OMNIVOROUS, } ``` -------------------------------- ### Update Validation Plugin to Zod Plugin in Pothos Source: https://pothos-graphql.dev/docs/migrations/v4 This example shows how to replace the deprecated `@pothos/plugin-validation` with the new `@pothos/plugin-zod`. It involves changing the import statement and updating the plugins array in the SchemaBuilder configuration. ```typescript - import ValidationPlugin from '@pothos/plugin-validation'; + import ZodPlugin from '@pothos/plugin-zod'; const builder = new SchemaBuilder({ - plugins: [ValidationPlugin], + plugins: [ZodPlugin], }); ``` -------------------------------- ### Define List Field with Array Type Source: https://pothos-graphql.dev/docs/guide/fields Creates a list field 'giraffes' by specifying the type as an array of 'Giraffe' objects. The resolver returns an array of objects matching the 'Giraffe' type. Another example shows a list of strings 'giraffeNames'. ```typescript builder.queryType({ fields: t => ({ giraffes: t.field({ description: 'multiple giraffes', type: ['Giraffe'], resolve: () => [{ name: 'Gina' }, { name: 'James' }], }), giraffeNames: t.field({ type: ['String'], resolve: () => ['Gina', 'James'], }) }), }); ``` -------------------------------- ### TypeScript Type Configuration for Pothos Builder Source: https://pothos-graphql.dev/docs/guide/troubleshooting Demonstrates how to define custom types for the Pothos SchemaBuilder, improving type safety and readability. Ensure your TypeScript is configured with `strict` mode enabled for better error detection. This example defines a `PothosTypes` interface to specify the shape of the context. ```typescript interface PothosTypes { Context: { user: { id: string; }; }; } const builder = new SchemaBuilder({...}); ``` -------------------------------- ### Create Prisma Connection Helpers for Media Type Source: https://pothos-graphql.dev/docs/plugins/prisma/connections This snippet demonstrates how to create connection helpers for a 'Media' type using `prismaConnectionHelpers`. It configures selections, node resolution, and connection-specific options like maxSize and defaultSize for the 'PostMedia' join table. ```javascript const Media = builder.prismaObject('Media', { select: { id: true, }, fields: (t) => ({ url: t.exposeString('url'), }), }); const mediaConnectionHelpers = prismaConnectionHelpers( builder, 'PostMedia', // this should be the the join table { cursor: 'id', select: (nodeSelection) => ({ // select the relation to the media node using the nodeSelection function media: nodeSelection({ // optionally specify fields to select by default for the node select: { id: true, posts: true, }, }), }), // resolve the node from the edge resolveNode: (postMedia) => postMedia.media, // additional/optional options maxSize: 100, defaultSize: 20, }, ); builder.prismaObjectField('Post', 'mediaConnection', (t) => t.connection({ // The type for the Node type: Media, // since we are not using t.relatedConnection we need to manually // include the selections for our connection select: (args, ctx, nestedSelection) => ({ media: mediaConnectionHelpers.getQuery(args, ctx, nestedSelection), }), resolve: (post, args, ctx) => // This helper takes a list of nodes and formats them for the connection mediaConnectionHelpers.resolve( // map results to the list of edges post.media, args, ctx, ), }), ); ``` -------------------------------- ### Customize ID Scalar Types in Pothos SchemaBuilder Source: https://pothos-graphql.dev/docs/migrations/v4 This example shows how to restore the default behavior for ID Scalar types in Pothos v4.0, aligning with previous versions. It allows `ID` input to be `number | string` and output to be `number | string`, preventing potential type mismatches. ```typescript import SchemaBuilder from '@pothos/core'; const builder = new SchemaBuilder<{ Scalars: { ID: { Input: number | string; Output: number | string; }; }; }>({}); ``` -------------------------------- ### Configure Prisma Plugin onNull Option Source: https://pothos-graphql.dev/docs/migrations/v4 Demonstrates configuring the `onNull` option for `t.relation` in the Pothos Prisma plugin. This option handles null relations on NonNullable fields. Examples include setting `onNull` to `'error'` to restore previous behavior, marking the field as `nullable: true`, or providing a function to load a placeholder or throw a custom error. ```typescript t.relation('nullableRelation', { onNull: 'error', }) ``` ```typescript t.relation('nullableRelation', { nullable: true, }) ``` ```typescript t.relation('nullableRelation', { onNull: () => loadPlaceholder(), }); ```