Policy
A class that ensures preconditions for a given route are respected.
Policies let you regulate routing for authentication or permissions-based reasons. This allows you to write authentication code in one place, use it in the router and not have to burden the rest of the codebase with it.
A Policy can also be used as a guard for a particular Controller action. For instance, you developed a REST API and you have a sub-resource, a policy can be created to ensure the parent exists.
Definition
- Library: tramway-core-router
- File: https://github.com/tramwayjs/router/blob/master/src/core/policies/Policy.js
Locations
- Implementation:
src/policies
- Dependency Injection:
src/config/services/policies.js
API
Function | Usage |
---|---|
constructor() | Sets a redirect via super(redirectRoute: string) |
check(request) | Implements and handles the check on the current status of user with regards to the policy. |
To create a policy, extend the class.
import { policies } from 'tramway-core-router';const { Policy } = policies;
To write an authentication policy, import the class and implement the stubs.
import { policies } from 'tramway-core-router';const { AuthenticationStrategy } = policies;
Example
import { policies, errors } from "tramway-core-router";const { Policy } = policies;const { HttpNotFoundError, HttpInternalServerError } = errors;export default class ProductPolicy extends Policy {constructor(productService, logger) {this.productService = productService;this.logger = logger;}async check(request) {let product;const {productId} = request.params || {};try {product = await this.productService.getOne(productId);} catch(e) {this.logger.error(e.stack);throw new HttpInternalServerError();}if (!product) {throw new HttpNotFoundError();}return { product };}}
Dependency Injection
import {ProductPolicy} from '../../policies';export default {"policy.product": {"class": ProductPolicy,"constructor": [{"type": "service", "key": "service.product"},{"type": "service", "key": "logger"},]}}