Migrating
@blocks/policy is the shared part of a pattern many apps already have: one class per resource, one method per action, every method returns a boolean. This page moves three common shapes of it onto the package. In each, the "before" is code you might have today and the "after" is the same rules on @blocks/policy.
From a package with an app-specific CurrentUser
The closest shape: an abstract Policy<TResource> whose constructor takes (user, resource), and a CurrentUser class with hasRole, isOwner and hasFlag, whose flag names are a union in the same file.
Before:
// policy.ts
import type { CurrentUser } from './current-user'
export abstract class Policy<TResource> {
constructor(
protected user: CurrentUser,
protected resource: TResource,
) {}
}
// current-user.ts
export type FeatureFlag = 'new-editor' | 'bulk-export'
export interface CurrentUserData {
id: string
role: string
flags?: Readonly<Partial<Record<FeatureFlag, boolean>>>
emailVerified?: boolean
}
export class CurrentUser {
readonly id: string
readonly role: string
readonly flags: Readonly<Partial<Record<FeatureFlag, boolean>>>
readonly emailVerified: boolean
constructor(data: CurrentUserData) {
this.id = data.id
this.role = data.role
this.flags = data.flags ?? {}
this.emailVerified = data.emailVerified ?? false
}
hasRole(...roles: string[]) {
return roles.includes(this.role)
}
isOwner(ownerId: string) {
return this.id === ownerId
}
hasFlag(name: FeatureFlag) {
return this.flags[name] === true
}
}After, keep both modules and their exports, and build them on the package. CurrentUser keeps only the field that is the app's own:
import { CurrentUser as BaseCurrentUser, type CurrentUserData as BaseCurrentUserData } from '@blocks/policy'
/** The app's flag names, as before. */
export type FeatureFlag = 'new-editor' | 'bulk-export'
export interface CurrentUserData extends BaseCurrentUserData<string, FeatureFlag> {
emailVerified?: boolean
}
/** hasRole, isOwner and hasFlag now come from @blocks/policy. Only the app's own field is left. */
export class CurrentUser extends BaseCurrentUser<string, FeatureFlag> {
readonly emailVerified: boolean
constructor(data: CurrentUserData) {
super(data)
this.emailVerified = data.emailVerified ?? false
}
}The app's Policy becomes one line that fixes the user type:
import { Policy as BasePolicy } from '@blocks/policy'
import type { CurrentUser } from './current-user'
/** The app's base policy, now one line: every policy's `this.user` is the app's CurrentUser. */
export abstract class Policy<TResource> extends BasePolicy<TResource, CurrentUser> {}The policies themselves do not change. They still import Policy from the app's own module, and this.user is still the app's CurrentUser, extra field included:
// Unchanged: it still imports the app's own Policy.
import { Policy } from './policy'
export interface Report {
ownerId: string
shared: boolean
}
export class ReportPolicy extends Policy<Report> {
view() {
return this.resource.shared || this.user.isOwner(this.resource.ownerId)
}
export() {
if (!this.user.emailVerified) return false
return this.user.hasFlag('bulk-export') && this.view()
}
}What changes:
hasRole,isOwnerandhasFlagcome from the package.hasRoleandhasFlagbehave as before.isOwneracceptsnullandundefined, and returnsfalsefor them and for the empty string. Before, it took only a string, and a user whose id was empty owned every resource whose owner was empty.this.userandthis.resourcearereadonly.- Role names can be typed too: extend
CurrentUser<Role, FeatureFlag>instead ofCurrentUser<string, FeatureFlag>. - Call sites do not change: you still ask a policy by calling its action, as in
if (!policy.update()). - If another service kept its own copy of these two modules because it could not depend on a workspace package, it can depend on
@blocks/policyfor the base classes instead.
From a package built on an options object
Here the base class takes one object, { user, organization, membership, resource }, and keeps each part. It defines helpers such as isAdmin() and isMember() from the membership, and policies add static methods so call sites can skip new.
Before:
export interface Resource {
id: string
[key: string]: any
}
export abstract class Policy<T extends Resource = Resource> {
protected readonly user: User
protected readonly organization: Organization
protected readonly membership: Membership | null
protected readonly resource: T
constructor(options: PolicyOptions<T>) {
this.user = options.user
this.organization = options.organization
this.membership = options.membership
this.resource = options.resource
}
protected isAdmin() {
return this.membership?.isAdmin() ?? false
}
protected isMember() {
return this.membership !== null
}
protected isViewer() {
return this.membership?.isViewer() ?? false
}
}
export class WorkspacePolicy extends Policy<WorkspaceResource> {
create() {
return this.isAdmin() || (this.isMember() && !this.isViewer())
}
delete() {
return this.isAdmin()
}
static delete(options: PolicyOptions<WorkspaceResource>) {
return new WorkspacePolicy(options).delete()
}
}
const allowed = WorkspacePolicy.delete({ user, organization, membership, resource: workspace })After, everything but the resource becomes the policy's user type, an Actor, and the helpers move to a base class in the app:
import { Policy } from '@blocks/policy'
import type { Membership, Organization, User } from './models'
/** Who is acting: what the old options object carried, minus the resource. */
export interface Actor {
user: User
organization: Organization
membership: Membership | null
}
/** The helpers the old base class had, now in the app. Protected, so code outside the policy cannot call them. */
export abstract class OrganizationPolicy<TResource> extends Policy<TResource, Actor> {
protected get membership() {
return this.user.membership
}
protected isAdmin() {
return this.membership?.role === 'admin'
}
protected isMember() {
return this.membership !== null
}
protected isViewer() {
return this.membership?.role === 'viewer'
}
}The policies keep their action bodies. The static helpers go, and call sites construct the policy and call the action:
import type { Membership, Organization, User } from './models'
import { OrganizationPolicy } from './organization-policy'
export interface Workspace {
id: string
organizationId: string
name: string
}
export class WorkspacePolicy extends OrganizationPolicy<Workspace> {
create() {
return this.isAdmin() || (this.isMember() && !this.isViewer())
}
update() {
return this.isAdmin() || (this.isMember() && !this.isViewer())
}
delete() {
return this.isAdmin()
}
}
// At the call site: construct the policy, the actor first and then the resource, and call the action.
export function canDeleteWorkspace(user: User, organization: Organization, membership: Membership | null, workspace: Workspace) {
return new WorkspacePolicy({ user, organization, membership }, workspace).delete()
}The user, organization and membership models stay in the app. The example uses simplified versions of them:
// The app's own models, simplified. They stay in the app, unchanged.
export interface User {
id: string
email: string
}
export interface Organization {
id: string
name: string
}
export interface Membership {
userId: string
organizationId: string
role: 'admin' | 'member' | 'viewer'
}What changes:
- The constructor takes two arguments, the actor and then the resource:
new WorkspacePolicy({ user, organization, membership }, workspace). this.useris the whole actor. A protectedmembershipgetter keepsthis.membershipworking in the helpers; add one fororganizationif your policies read it.- The resource no longer has to fit a
Resourceinterface with anidand an index signature. Any type works. - The static methods go. Construct the policy and call the action,
new WorkspacePolicy(actor, workspace).delete(), without writing a helper per action. - Policies the package used to ship move into the app with the rest of its rules.
From pundit.js
pundit.js, the pundit package on npm, is a JavaScript port of Ruby's Pundit, and @blocks/policy follows both. Its policies are classes too, so the move is small.
Before:
import { Policy } from 'pundit'
export default class PostPolicy extends Policy {
constructor(user, record) {
super(user, record)
this.setup.apply(this)
}
edit() {
return this.user.id === this.record.userId
}
destroy() {
return this.user.isAdmin
}
}
const postPolicy = new PostPolicy(user, post)
postPolicy.can('edit')After:
import { Policy } from '@blocks/policy'
interface User {
id: number
isAdmin: boolean
}
interface Post {
id: number
userId: number
}
export class PostPolicy extends Policy<Post, User> {
edit() {
return this.user.id === this.resource.userId
}
destroy() {
return this.user.isAdmin
}
}
const user = { id: 1, isAdmin: false }
const post = { id: 11, userId: 1 }
const postPolicy = new PostPolicy(user, post)
export const canEdit = postPolicy.edit() // true
export const canDestroy = postPolicy.destroy() // falseWhat changes:
recordbecomesresource:this.record.userIdisthis.resource.userId.- There is no
setup. Delete the constructor; each method you add is an action. - There is no
can. Ask by calling the action:postPolicy.edit()instead of passing'edit'as a string. A misspelled or unknown action is then a compile error rather thanfalse. - The user and the resource are typed:
Policy<Post, User>. Your user can stay a plain object, as here. - There is no
addfor actions defined at runtime. Write them as methods. - There is no
copy. To ask about another user or record, construct a new policy:new PostPolicy(otherUser, post). - No React components are bundled. Replace
Whenwith conditional rendering from the action's boolean,{policy.edit() && <EditButton />}, andPunditProviderwith passing the policy, or booleans, where you need them.