Stone.js API
    Preparing search index...

    Interface IPolicy<EventType>

    The contract a policy class exposes.

    One method, authorize(event), returning whether the caller may proceed. It receives the event, so a policy can load the record it protects, and it is resolved by the container, so its constructor receives the services it needs to do that:

    @Policy('post.update')
    export class UpdatePostPolicy implements IPolicy {
    constructor ({ posts }: { posts: PostService }) { this.posts = posts }
    async authorize (event) {
    const post = await this.posts.find(event.get('id'))
    return post.authorId === event.getMetadataValue('auth')?.sub
    }
    }

    That is the case an ability alone cannot express: "may update this post" needs the post. An ability answers what a role may do; a policy answers what this caller may do to this record.

    The event type is a parameter because a policy reads its event: implements IPolicy<IncomingHttpEvent> types authorize (event) as that event, headers and cookies included. Without it, narrowing the parameter in an implementation is rejected outright, since a function-typed property is contravariant on its parameters, and an application had to drop the implements clause to write what it meant.

    interface IPolicy<EventType extends IncomingEvent = IncomingEvent> {
        authorize: (event: EventType) => boolean | Promise<boolean>;
    }

    Type Parameters

    • EventType extends IncomingEvent = IncomingEvent
    Index
    authorize: (event: EventType) => boolean | Promise<boolean>

    Whether the caller may proceed.