Skip to content

index.Function.createCan

github-actions[bot] edited this page Nov 30, 2026 · 26 revisions

Function: createCan()

Call Signature

function createCan<TContext, TSubjectMap>(
   getAbility, 
   isAuthenticated, 
   buildSubject, 
options?): RequireCan<TSubjectMap>;

Defined in: packages/graphql-casl/src/createCan.ts:431

Factory that returns a requireCan(action, subject, getSubjectData?) rule builder bound to a specific ability resolver and subject map.

Type Parameters

TContext

TContext

Your resolver context type.

TSubjectMap

TSubjectMap extends Record<string, object>

The subject map, e.g. SubjectMap<Resolvers, ResolversTypes>.

Parameters

getAbility

(context) => Promise<AbilityLike>

Builds the ability for a request's context. Memoized per context.

isAuthenticated

(context) => boolean

Returns whether the context represents a logged-in caller.

buildSubject

BuildSubject<TSubjectMap>

Optional subject constructor, typically createTyped's typed.

options?

CreateCanOptions

Optional CreateCanOptions. May be passed in buildSubject's position when no tagger is used.

Returns

RequireCan<TSubjectMap>

A requireCan(action, subject, getSubjectData?) builder.

Remarks

This decouples the auth/ability logic from the permissions map so projects can swap in any ability-building strategy. The returned builder produces a Rule that:

  1. throws Not authenticated when isAuthenticated returns false;
  2. builds the request's ability via getAbility;
  3. throws Forbidden when the ability denies the action;
  4. otherwise calls the wrapped resolver.

When getSubjectData and buildSubject are both supplied, the checked subject is buildSubject(subject, getSubjectData(args, parent)) (e.g. a typed() instance); with neither it is the bare subject-name string, which checks whether the action is possible on that subject type rather than permitted on a specific one — see UnconditionedSubjectMode.

Caveat on parent. Under plain graphql-js execution a parent resolver returns its whole object, so a field rule reliably sees the fields it reads. That stops being true when the parent resolver projects by the selection set — a Prisma select built from info, or schema delegation — because a field the client did not request may simply be absent, and an absent field makes a CASL condition fail rather than error. Neither graphql-middleware's fragment option nor anything this library can do from inside a rule fixes that: the parent has already resolved by the time a field rule runs. If your resolvers project, have the parent select the fields your rules condition on.

getAbility is called at most once per context object: every rule from a given factory shares the result, so a query touching many guarded fields builds the ability once. A rejected build is not cached.

Example

const canUser = createCan<Context, AppSubjectMap>(
  async (ctx) => defineAbilitiesFor(ctx.userId),
  (ctx) => ctx.userId != null,
  typed,
);

// bare subject:
const readUser = canUser(Actions.read, Subject.User);
// subject instance built from args (annotate `args` to type the extraction):
const updateNote = canUser(Actions.update, Subject.Note, (args: MutationUpdateNoteArgs) => ({
  userId: args.userId,
}));

Call Signature

function createCan<TContext, TSubjectMap>(
   getAbility, 
   isAuthenticated, 
options?): RequireCanBare<TSubjectMap>;

Defined in: packages/graphql-casl/src/createCan.ts:437

Factory that returns a requireCan(action, subject, getSubjectData?) rule builder bound to a specific ability resolver and subject map.

Type Parameters

TContext

TContext

Your resolver context type.

TSubjectMap

TSubjectMap extends Record<string, object>

The subject map, e.g. SubjectMap<Resolvers, ResolversTypes>.

Parameters

getAbility

(context) => Promise<AbilityLike>

Builds the ability for a request's context. Memoized per context.

isAuthenticated

(context) => boolean

Returns whether the context represents a logged-in caller.

options?

CreateCanOptions

Optional CreateCanOptions. May be passed in buildSubject's position when no tagger is used.

Returns

RequireCanBare<TSubjectMap>

A requireCan(action, subject, getSubjectData?) builder.

Remarks

This decouples the auth/ability logic from the permissions map so projects can swap in any ability-building strategy. The returned builder produces a Rule that:

  1. throws Not authenticated when isAuthenticated returns false;
  2. builds the request's ability via getAbility;
  3. throws Forbidden when the ability denies the action;
  4. otherwise calls the wrapped resolver.

When getSubjectData and buildSubject are both supplied, the checked subject is buildSubject(subject, getSubjectData(args, parent)) (e.g. a typed() instance); with neither it is the bare subject-name string, which checks whether the action is possible on that subject type rather than permitted on a specific one — see UnconditionedSubjectMode.

Caveat on parent. Under plain graphql-js execution a parent resolver returns its whole object, so a field rule reliably sees the fields it reads. That stops being true when the parent resolver projects by the selection set — a Prisma select built from info, or schema delegation — because a field the client did not request may simply be absent, and an absent field makes a CASL condition fail rather than error. Neither graphql-middleware's fragment option nor anything this library can do from inside a rule fixes that: the parent has already resolved by the time a field rule runs. If your resolvers project, have the parent select the fields your rules condition on.

getAbility is called at most once per context object: every rule from a given factory shares the result, so a query touching many guarded fields builds the ability once. A rejected build is not cached.

Example

const canUser = createCan<Context, AppSubjectMap>(
  async (ctx) => defineAbilitiesFor(ctx.userId),
  (ctx) => ctx.userId != null,
  typed,
);

// bare subject:
const readUser = canUser(Actions.read, Subject.User);
// subject instance built from args (annotate `args` to type the extraction):
const updateNote = canUser(Actions.update, Subject.Note, (args: MutationUpdateNoteArgs) => ({
  userId: args.userId,
}));

API Reference

Clone this wiki locally