UNPKG

2.16 kBJavaScriptView Raw
1const { chalk } = require('./../namespace/console');
2const path = require('path');
3const debug = require('debug');
4
5module.exports = class Policy {
6
7 constructor (policies, logging, server, policy, controller, action) {
8 this.policy = policy;
9 this.controller = controller;
10 this.action = action;
11 this.server = server;
12 this.policies = policies;
13 this.logging = logging;
14 this.debug = debug('glad');
15 }
16
17 restrict (req, res) {
18 this.debug('Policy: evaluating > %s', req.id);
19 req.controller = this.controller.name;
20 req.action = this.action;
21
22 if (this.logging) {
23 chalk.info(`Routing ${req.id} to ${this.controller.name}#${this.action}`);
24 }
25
26 if (this.policy) {
27 this.debug('Policy: lookup %s > %s', this.policy, req.id);
28 if (this.policies[this.policy]) {
29 this.debug('Policy: apply %s > %s', this.policy, req.id);
30 this.policies[this.policy](req, res, this.acceptor(req, res), this.rejector(req, res));
31 } else {
32 this.debug('Policy: %s not found [error] %s', this.policy, req.id);
33 chalk.error(`Policy Error: ${req.id || ''} The policy "${this.policy}" does not exist, therefore the request was denied`);
34 this.policies.onFailure(req, res);
35 }
36 } else {
37 this.debug('Policy: no policy to apply > %s', req.id);
38 this.runControllerMethod(req, res);
39 }
40 }
41
42 acceptor (req, res) {
43 return () => {
44 this.debug('Policy:accept > %s', req.id);
45 this.runControllerMethod(req, res);
46 };
47 }
48
49 rejector (req, res) {
50 return (custom) => {
51 this.debug('Policy:reject > %s', req.id);
52 return this.policies.onFailure(req, res, custom)
53 };
54 }
55
56 runControllerMethod (req, res) {
57 this.debug('Policy:runControllerMethod > %s', req.id);
58 let controller = new this.controller(req, res, this.server.redis);
59 if (controller[this.action]) {
60 controller[this.action]();
61 } else {
62 chalk.error(`Routing Error: ${req.id || ''} Can not route request to "${req.controller}#${req.action}" because ${req.action} does not exist on ${req.controller}`);
63 this.policies.onFailure(req, res);
64 }
65 }
66
67}