Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add support for validation plugin in Pothos
  • Loading branch information
kingston committed Nov 20, 2025
commit cd2c518e0dfb4b534e76bb19740cf33a70377581
1 change: 1 addition & 0 deletions examples/todo-with-auth0/apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"@pothos/plugin-relay": "4.6.2",
"@pothos/plugin-simple-objects": "4.1.3",
"@pothos/plugin-tracing": "1.1.0",
"@pothos/plugin-validation": "4.2.0",
"@pothos/tracing-sentry": "1.1.1",
"@prisma/adapter-pg": "6.17.1",
"@prisma/client": "6.17.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { PothosFieldWithInputPayloadPlugin } from './index.js';
import type {
MutationWithInputPayloadOptions,
OutputShapeFromFields,
PayloadFieldRef,
} from './types.js';

declare global {
Expand Down Expand Up @@ -56,10 +57,7 @@ declare global {
payload: RootFieldBuilder<Types, unknown, 'PayloadObject'>;
fieldWithInputPayload: <
InputFields extends InputFieldMap,
PayloadFields extends Record<
string,
FieldRef<Types, unknown, 'PayloadObject'>
>,
PayloadFields extends Record<string, PayloadFieldRef<Types, unknown>>,
ResolveShape,
ResolveReturnShape,
Args extends InputFieldMap = Record<never, never>,
Expand All @@ -79,7 +77,7 @@ declare global {
ShapeFromTypeParam<
Types,
ObjectRef<Types, OutputShapeFromFields<PayloadFields>>,
false
Types['DefaultFieldNullability']
>
>;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {

import { capitalizeString } from '@src/utils/string.js';

import type { PayloadFieldRef } from './types.js';

const rootBuilderProto =
RootFieldBuilder.prototype as PothosSchemaTypes.RootFieldBuilder<
SchemaTypes,
Expand All @@ -27,11 +29,11 @@ rootBuilderProto.fieldWithInputPayload = function fieldWithInputPayload({
// expose all fields of payload by default
const payloadFields = (): Record<
string,
FieldRef<SchemaTypes, unknown, 'PayloadObject'>
PayloadFieldRef<SchemaTypes, unknown>
> => {
for (const key of Object.keys(payload)) {
payload[key].onFirstUse((cfg) => {
if (cfg.kind === 'Object') {
if (cfg.kind === 'Object' && !cfg.resolve) {
cfg.resolve = (parent) =>
(parent as Record<string, unknown>)[key] as Readonly<unknown>;
}
Expand All @@ -56,16 +58,19 @@ rootBuilderProto.fieldWithInputPayload = function fieldWithInputPayload({
type: payloadRef,
nullable: false,
...fieldOptions,
} as never);
} as never) as FieldRef<SchemaTypes, never, 'Mutation'>;

fieldRef.onFirstUse((config) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fieldRef.onFirstUse((config: any) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
const capitalizedName = capitalizeString(config.name);
const inputName = `${capitalizedName}Input`;
const payloadName = `${capitalizedName}Payload`;

if (inputRef) {
inputRef.name = inputName;
this.builder.inputType(inputRef, {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
description: `Input type for ${config.name} mutation`,
fields: () => input,
});
Expand All @@ -74,6 +79,7 @@ rootBuilderProto.fieldWithInputPayload = function fieldWithInputPayload({
payloadRef.name = payloadName;
this.builder.objectType(payloadRef, {
name: payloadName,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
description: `Payload type for ${config.name} mutation`,
fields: payloadFields,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ import type {
SchemaTypes,
} from '@pothos/core';

export type PayloadFieldRef<Types extends SchemaTypes, T> = Omit<
FieldRef<Types, T, 'PayloadObject'>,
'validate'
>;

export type OutputShapeFromFields<Fields extends FieldMap> =
NullableToOptional<{
[K in keyof Fields]: Fields[K] extends GenericFieldRef<infer T> ? T : never;
Expand All @@ -23,7 +28,7 @@ export type MutationWithInputPayloadOptions<
Kind extends FieldKind,
Args extends InputFieldMap,
InputFields extends InputFieldMap,
PayloadFields extends Record<string, FieldRef<Types, unknown, 'Object'>>,
PayloadFields extends Record<string, PayloadFieldRef<Types, unknown>>,
ResolveShape,
ResolveReturnShape,
> = Omit<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import PrismaPlugin from '@pothos/plugin-prisma';
import RelayPlugin from '@pothos/plugin-relay';
import SimpleObjectsPlugin from '@pothos/plugin-simple-objects';
import TracingPlugin, { isRootField } from '@pothos/plugin-tracing';
import ValidationPlugin from '@pothos/plugin-validation';
import { createSentryWrapper } from '@pothos/tracing-sentry';

import type PrismaTypes from '@src/generated/prisma/pothos-prisma-types.js';
Expand Down Expand Up @@ -57,6 +58,7 @@ export const builder = new SchemaBuilder<{
pothosStripQueryMutationPlugin,
RelayPlugin,
SimpleObjectsPlugin,
ValidationPlugin,
],
prisma: {
client: prisma,
Expand Down
14 changes: 14 additions & 0 deletions examples/todo-with-auth0/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export const FASTIFY_PACKAGES = {
'@pothos/plugin-simple-objects': '4.1.3',
'@pothos/plugin-relay': '4.6.2',
'@pothos/plugin-prisma': '4.12.0',
'@pothos/plugin-validation': '4.2.0',
'graphql-scalars': '1.23.0',

'@graphql-yoga/redis-event-target': '2.0.0',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
}
},
"pathRootRelativePath": "{src-root}/plugins/graphql/FieldWithInputPayloadPlugin/schema-builder.ts",
"referencedGeneratorTemplates": ["field-with-input-types"],
"sourceFile": "src/plugins/graphql/FieldWithInputPayloadPlugin/schema-builder.ts",
"variables": {}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ const fieldWithInputSchemaBuilder = createTsTemplateFile({
group: 'field-with-input-payload',
importMapProviders: { tsUtilsImports: tsUtilsImportsProvider },
name: 'field-with-input-schema-builder',
referencedGeneratorTemplates: { fieldWithInputTypes: {} },
source: {
path: path.join(
import.meta.dirname,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ export const pothosGenerator = createGenerator({
'@pothos/core',
'@pothos/plugin-simple-objects',
'@pothos/plugin-relay',
'@pothos/plugin-validation',
]),
}),
main: createGeneratorTask({
Expand Down Expand Up @@ -221,6 +222,12 @@ export const pothosGenerator = createGenerator({
.default('RelayPlugin')
.from('@pothos/plugin-relay'),
),
validationPlugin: tsCodeFragment(
`ValidationPlugin`,
tsImportBuilder()
.default('ValidationPlugin')
.from('@pothos/plugin-validation'),
),
};

const schemaOptionsFragment = TsCodeUtils.mergeFragmentsAsObject({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { PothosFieldWithInputPayloadPlugin } from '$fieldWithInputPlugin';
import type {
MutationWithInputPayloadOptions,
OutputShapeFromFields,
PayloadFieldRef,
} from '$fieldWithInputTypes';
import type {
FieldKind,
Expand Down Expand Up @@ -57,10 +58,7 @@ declare global {
payload: RootFieldBuilder<Types, unknown, 'PayloadObject'>;
fieldWithInputPayload: <
InputFields extends InputFieldMap,
PayloadFields extends Record<
string,
FieldRef<Types, unknown, 'PayloadObject'>
>,
PayloadFields extends Record<string, PayloadFieldRef<Types, unknown>>,
ResolveShape,
ResolveReturnShape,
Args extends InputFieldMap = Record<never, never>,
Expand All @@ -80,7 +78,7 @@ declare global {
ShapeFromTypeParam<
Types,
ObjectRef<Types, OutputShapeFromFields<PayloadFields>>,
false
Types['DefaultFieldNullability']
>
>;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @ts-nocheck

import type { PayloadFieldRef } from '$fieldWithInputTypes';
import type { FieldRef, SchemaTypes } from '@pothos/core';

import { capitalizeString } from '%tsUtilsImports';
Expand Down Expand Up @@ -28,11 +29,11 @@ rootBuilderProto.fieldWithInputPayload = function fieldWithInputPayload({
// expose all fields of payload by default
const payloadFields = (): Record<
string,
FieldRef<SchemaTypes, unknown, 'PayloadObject'>
PayloadFieldRef<SchemaTypes, unknown>
> => {
for (const key of Object.keys(payload)) {
payload[key].onFirstUse((cfg) => {
if (cfg.kind === 'Object') {
if (cfg.kind === 'Object' && !cfg.resolve) {
cfg.resolve = (parent) =>
(parent as Record<string, unknown>)[key] as Readonly<unknown>;
}
Expand All @@ -57,16 +58,19 @@ rootBuilderProto.fieldWithInputPayload = function fieldWithInputPayload({
type: payloadRef,
nullable: false,
...fieldOptions,
} as never);
} as never) as FieldRef<SchemaTypes, never, 'Mutation'>;

fieldRef.onFirstUse((config) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fieldRef.onFirstUse((config: any) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
const capitalizedName = capitalizeString(config.name);
const inputName = `${capitalizedName}Input`;
const payloadName = `${capitalizedName}Payload`;

if (inputRef) {
inputRef.name = inputName;
this.builder.inputType(inputRef, {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
description: `Input type for ${config.name} mutation`,
fields: () => input,
});
Expand All @@ -75,6 +79,7 @@ rootBuilderProto.fieldWithInputPayload = function fieldWithInputPayload({
payloadRef.name = payloadName;
this.builder.objectType(payloadRef, {
name: payloadName,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
description: `Payload type for ${config.name} mutation`,
fields: payloadFields,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import type {
SchemaTypes,
} from '@pothos/core';

export type PayloadFieldRef<Types extends SchemaTypes, T> = Omit<
FieldRef<Types, T, 'PayloadObject'>,
'validate'
>;

export type OutputShapeFromFields<Fields extends FieldMap> =
NullableToOptional<{
[K in keyof Fields]: Fields[K] extends GenericFieldRef<infer T> ? T : never;
Expand All @@ -25,7 +30,7 @@ export type MutationWithInputPayloadOptions<
Kind extends FieldKind,
Args extends InputFieldMap,
InputFields extends InputFieldMap,
PayloadFields extends Record<string, FieldRef<Types, unknown, 'Object'>>,
PayloadFields extends Record<string, PayloadFieldRef<Types, unknown>>,
ResolveShape,
ResolveReturnShape,
> = Omit<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,9 +241,9 @@ export function generateCreateSchema<
TFields extends Record<string, AnyFieldDefinition>,
>(fields: TFields): InferInputSchema<TFields> {
const shape = Object.fromEntries(
Object.entries(fields).map(([key, field]) => [key, field.zodSchema]),
Object.entries(fields).map(([key, field]) => [key, field.schema]),
) as {
[K in keyof TFields]: TFields[K]['zodSchema'];
[K in keyof TFields]: TFields[K]['schema'];
};

return z.object(shape);
Expand Down Expand Up @@ -613,7 +613,7 @@ type UpdateOperationFunction<
input: UpdateOperationInput<TModelName, TFields, TQueryArgs>,
) => Promise<GetPayload<TModelName, TQueryArgs>>) & {
$dataSchema: z.ZodObject<{
[k in keyof TFields]: z.ZodOptional<TFields[k]['zodSchema']>;
[k in keyof TFields]: z.ZodOptional<TFields[k]['schema']>;
}>;
};
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@ import type {
TransactionalOperationContext,
} from '$types';
import type { Payload } from '@prisma/client/runtime/client';
import type { z } from 'zod';

import { invokeHooks, transformFields } from '$defineOperations';
import {
generateCreateSchema,
invokeHooks,
transformFields,
} from '$defineOperations';
import { makeGenericPrismaDelegate } from '$prismaUtils';
import { prisma } from '%prismaImports';
import { z } from 'zod';

/**
* Create a simple scalar field with validation and optional transformation
Expand Down Expand Up @@ -73,7 +77,7 @@ export function scalarField<
},
): FieldDefinition<TSchema, TTransformed, TTransformed> {
return {
zodSchema: schema,
schema,
processInput: (value) => {
// Apply transform if provided
const transformed = options?.transform
Expand Down Expand Up @@ -265,16 +269,7 @@ export function nestedOneToOneField<
undefined | { delete: true }
> {
return {
zodSchema: (
z.object(
Object.fromEntries(
Object.entries(config.fields).map(([key, field]) => [
key,
field.zodSchema,
]),
),
) as InferInputSchema<TFields>
).nullish(),
schema: generateCreateSchema(config.fields).nullish(),
processInput: async (value, processCtx) => {
// Handle null - delete the relation
if (value === null) {
Expand Down Expand Up @@ -594,18 +589,7 @@ export function nestedOneToManyField<
};

return {
zodSchema: z
.array(
z.object(
Object.fromEntries(
Object.entries(config.fields).map(([key, field]) => [
key,
field.zodSchema,
]),
),
) as InferInputSchema<TFields>,
)
.optional(),
schema: generateCreateSchema(config.fields).array().optional(),
processInput: async (value, processCtx) => {
const { serviceContext, loadExisting } = processCtx;

Expand Down
Loading