1 | export class RouterGuardService {
|
2 | constructor(to, from, isHook = false) {
|
3 | this.guardCallbacks = [];
|
4 | this.isCancelled = false;
|
5 | this.lastContext = null;
|
6 | this.isHook = false;
|
7 | this.setRoutes(to, from);
|
8 | this.isHook = isHook;
|
9 | }
|
10 | add(callback) {
|
11 | this.guardCallbacks.push(callback);
|
12 | }
|
13 | async executeCallbacks(arr, predicate) {
|
14 | for (const e of arr) {
|
15 | if (await predicate(e)) {
|
16 | return true;
|
17 | }
|
18 | }
|
19 | return false;
|
20 | }
|
21 | run() {
|
22 | this.lastContext = true;
|
23 | const next = (vmContext) => {
|
24 | if (typeof vmContext === "undefined") {
|
25 | return;
|
26 | }
|
27 | this.lastContext = vmContext;
|
28 | if (vmContext === false) {
|
29 | this.isCancelled = true;
|
30 | }
|
31 | };
|
32 | this.executeCallbacks(this.guardCallbacks.filter((callback) => typeof callback === "function"), async (callback) => {
|
33 | if (this.isCancelled) {
|
34 | return true;
|
35 | }
|
36 | let result = null;
|
37 | if (this.isHook) {
|
38 | const hookCallback = callback;
|
39 | await hookCallback(this.routeTo, this.routeFrom);
|
40 | }
|
41 | else if (callback &&
|
42 | typeof callback.then === "function") {
|
43 | result = await callback(this.routeTo, this.routeFrom, next);
|
44 | }
|
45 | else {
|
46 | result = callback(this.routeTo, this.routeFrom, next);
|
47 | }
|
48 | if (result === false) {
|
49 | this.isCancelled = true;
|
50 | this.lastContext = false;
|
51 | return true;
|
52 | }
|
53 | if (result && result !== true) {
|
54 | this.isCancelled = true;
|
55 | this.lastContext = result;
|
56 | return true;
|
57 | }
|
58 | return false;
|
59 | });
|
60 | return this.lastContext;
|
61 | }
|
62 | setRoutes(to, from) {
|
63 | this.routeTo = to;
|
64 | this.routeFrom = from;
|
65 | this.isCancelled = false;
|
66 | }
|
67 | }
|
68 |
|
\ | No newline at end of file |