From f620b0f9517e155442a974fee02ba26a630235fc Mon Sep 17 00:00:00 2001 From: Markus Felten Date: Thu, 20 Jun 2024 23:05:08 +0200 Subject: [PATCH] add missing src/guard.mjs from template --- src/guard.mjs | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/guard.mjs diff --git a/src/guard.mjs b/src/guard.mjs new file mode 100644 index 0000000..4c07259 --- /dev/null +++ b/src/guard.mjs @@ -0,0 +1,72 @@ +/** + * Enforces conditions of routes + * Like the presents of values in the context + */ +export class Guard { + /** + * Called while entering a route (current outlet is not yet set) + * @param {Transition} transition + */ + async enter(transition) {} + + /** + * Called before leaving a route + * @param {Transition} transition + */ + async leave(transition) {} + + toString() { + return this.constructor.name; + } +} + +/** + * Redirects to a given path if condition is met. + * + * @param {string} path + * @param {Function} condition redirects when returning true + */ +export function redirectGuard(path, condition) { + return { + toString: () => `redirect(${path})`, + enter: async transition => { + if (condition === undefined || condition(transition)) { + return transition.redirect(path); + } + }, + leave: () => {} + }; +} + +/** + * Execute guards in a sequence. + * @param {Iterable} children + */ +export function sequenceGuard(children) { + return { + toString: () => children.toString(), + enter: async transition => { + for (const child of children) { + await child.enter(transition); + } + }, + leave: async transition => { + for (const child of children) { + await child.leave(transition); + } + } + }; +} + +/** + * Execute guards in a parallel. + * @param {Iterable} children + */ +export function parallelGuard(children) { + return { + enter: async transition => + Promise.all([...children].map(c => c.enter(transition))), + leave: async transition => + Promise.all([...children].map(c => c.leave(transition))) + }; +}