Happy New Year's Eve. I've been developing recently. I don't have time to write a blog at the front and back ends. I'm just taking out the interceptor I've recently studied to show off ~
What is an interceptor?
Generally speaking, it is forbidden to visit a group of pages when a group of conditions are not met; Let's take chestnuts for example. I have a page whose path is dioxide CN ink/view/demo. HTML, I only hope that the readers who like me can access it, so the readers who don't like it can't access it. In this way, we can intercept the readers who don't like it outside the page;
We learned the interceptor of Springboot and the page routing of Vue in the second grade of primary school. We follow the wisdom of our predecessors. Now let's realize the function of an interceptor through native js, and make it easier to configure and understand. In order to improve the initiative of learning, the example code uses a "chain call of functions", "development of classes and objects" and "synchronous call of ajax in class methods", which may not be suitable for readers who are just starting js ~
Idea and structure:
In the above, we mentioned the saying "when a group of conditions are not met, it is forbidden to visit a group of pages", We can directly analyze the properties of the object - this object needs "a set of conditions", "page redirected after being intercepted" and "a set of intercepted target pages". Then let's implement this object first:
group1: { desc: 'need token To access', redirect: '404', pages: [ '/view/demo.html' ] }
To facilitate reading, we added a desc attribute to annotate what conditions the group needs to access the pages. In this way, we get a set of requirements, but it seems that we need to configure many groups of different weighted configurations. Then we can construct an object or an object array externally to store these configuration objects. For the convenience of narration, we will encapsulate it in the pages object as a nested object;
Obviously, to implement the interception method of group1, we need to analyze the following methods from the defined configuration:
- Detect that the currently accessed page is in the pages array;
- If so, we need to judge whether group1 meets the permissions we need;
- If the permission is also met, we will allow visitors to stay on the page, otherwise they will be redirected to 404 HTML page;
Theory exists and practice begins. In order to improve readability and understanding, we define two classes (Util tool class and Condition condition class). The Condition class is used to define some Condition judgment methods, and their return values are Boolean types; The tool class is used to store some data processing and comprehensive judgment of Condition groups (such as redirection page, interceptor encapsulation, etc.);
Since the tool class needs to call the method of the Condition class, we need to let Util inherit the method of Condition. Now let's construct these two classes:
class Condition {} class Util extends Condition {}
Our class method has been conceived. Now we use token as an example (I have written the verification interface of token with springboot on the back end, and the front-end token is stored in a cookie). In this way, our condition is to intercept all users who do not have or forge a token. Here, we use the chain function to first judge whether there is a token, and then judge whether the token is valid; Considering that there may be more than one condition, we need to define a condition group judge to judge the return results of all incoming conditions, that is, one no, all no, all true is true. Now let's implement these codes:
/** * condition Condition base * @author Dioxide.CN 2022/1/31 */ class Condition { /** * Verify whether the token is valid * @return {Boolean} true: Effective; false: does not exist or is invalid; */ trueToken() { if(this.tokenStatue){ var ret = true $.ajax({ async: false, //Synchronous execution url: 'http://localhost/verifyToken', type: 'post', data: { 'token': $.cookie('token') }, success: function(res) { ret = res } }) return ret } else { return false } } /** * @java public boolean ifToken(){} * @retun {Boolean} true: In the page; false: not in the page; */ ifPage(pages) { var curr = window.location.pathname for(var key in pages) { if(curr.indexOf(pages[key])==0) { return true } } return false } } /** * util Tool library * @author Dioxide.CN 2022/1/31 */ class Util extends Condition { /** * Is there a token * @return {Boolean} true: Existence; false: does not exist; */ ifToken() { if($.cookie('token') == undefined) { this.tokenStatue = false } else { this.tokenStatue = true } return this } /** * Redirection method * @param {String} page Target page name */ redirectTo(page) { window.open('/' + page + '.html','_self'); } /** * Condition set * @param {Array} Condition return group; Boolean two-dimensional array * @return {Boolean} true: The condition set is true; False: the condition set is false; */ getBoolean(...bool) { var last = true for(var key of bool[0]) { last = last && key } return last } /** * It can only be accessed when it is within the page and the condition set is true * @java public void intercept(){} * @param {Object} target Configuration group * @param {Array} condition Condition set */ intercept(target, ...condition) { if(this.ifPage(target.pages)) { if(!this.getBoolean(condition)) { this.redirectTo(target.redirect) } } }} }
< code > util Intercept() < / code > is the interceptor driver we need. With these judgments, we can easily realize various interceptor functions we want:
const util = new Util() //Instantiate util /** * Interception area * @example util.intercept(Configuration group, condition set) * @example util.intercept(pages.group1,util.ifToken().trueToken()) */ util.intercept(pages.group1,util.ifToken().trueToken())
In this way, we have completed the function of interceptor realized by native js ~