Repository navigation
index.Function.validateArgs
function validateArgs<TSchema>(schema, options?): Rule;Defined in: packages/graphql-casl/src/validateArgs.ts:217
A rule that validates a field's arguments against a Standard Schema, and on
success calls the resolver with the parsed output as its args.
TSchema extends StandardSchemaV1<unknown, unknown>
The Standard Schema. Its output type is what the resolver receives; ValidatedArgs names it.
TSchema
Any object with a ~standard property: a zod, valibot,
arktype or yup schema, or a hand-written one.
See ValidateArgsOptions.
A rule; not checkable.
GraphQL's own input coercion checks shape — the right scalars in the right
places. It has nothing to say about a title that is blank, an end date before
its start, or a page size of ten million. Those checks usually end up
hand-written at the top of each resolver; validateArgs lifts them into the
permissions map, next to the authorization the same field needs, and gives
the resolver the parsed arguments — trimmed, defaulted, coerced — rather
than the raw ones.
A failure is not a permission denial. It rejects with a GraphQLError
whose message lists the issues, with extensions.code set to
BAD_USER_INPUT and extensions.issues holding each one as an
ArgumentIssue. The error control on applyPermissions leaves it
verbatim: fallbackError never rewords it — it named its own error — and
under onDeny: 'filter' it keeps its own code rather than taking
UNAUTHORIZED_FIELD_OR_TYPE. Under onDeny: 'mask' it is masked like any
other refusal, so bad input then reads as a missing record; that is the
trade-off 'mask' already makes. An error thrown by the validator itself
is a rule failure, not a validation result, and surfaces as one.
Because it rewrites arguments and calls the resolver, it is a plain
Rule, not a CheckableRule: it cannot be an operand of and / or /
not / chain / race. Compose it with wrap — the authorization rule
first, so a caller who may not run the field at all learns that rather than
what is wrong with their input:
Mutation: {
createNote: wrap(canUser(Actions.create, Subject.Note), validateArgs(CreateNoteArgs)),
}Rewritten arguments bypass GraphQL's coercion, exactly as scopeArgs's do.
The schema's output is what the resolver gets, so a transform that changes a
value's type — a string to a Date, say — hands the resolver something the
SDL never promised. That is often the point; just make sure the resolver
expects it.
import { z } from 'zod';
import { validateArgs, wrap } from '@vantreeseba/graphql-casl';
const CreateNoteArgs = z.object({
input: z.object({
title: z.string().trim().min(1, 'A note needs a title'),
tags: z.array(z.string()).max(10).default([]),
}),
});
const permissions = {
Mutation: {
createNote: wrap(canUser(Actions.create, Subject.Note), validateArgs(CreateNoteArgs)),
},
} satisfies PermissionsMap<Resolvers>;