icore 0.1.38 → 1.0.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/route.js DELETED
@@ -1,109 +0,0 @@
1
- const EventEmitter = require('events');
2
- const TypeEnforcement = require('type-enforcement');
3
- const AsyncFunction = require('./async-function');
4
-
5
- const te = new TypeEnforcement({
6
- 'constructor: new Route()': {
7
- method: String,
8
- handler: AsyncFunction,
9
- finish: Boolean
10
- }
11
- });
12
-
13
- /**
14
- * RFC 3986 2.2. Reserved Characters
15
- * ":" "/" "?" "#" "[" "]" "@"
16
- *
17
- */
18
-
19
- const re = {
20
- rfc398622: /[^\x21\x22\x24-\x2E\x30-\x39\x3B-\x3E\x41-\x5A\x5C\x5E-\x7E]/
21
- };
22
-
23
- class Route extends EventEmitter {
24
- constructor({path = '', method = 'get', handler, finish = false}) {
25
- super();
26
-
27
- const err = te.validate('constructor: new Route()', {
28
- method,
29
- handler,
30
- finish
31
- });
32
-
33
- if (err) {
34
- throw err;
35
- }
36
-
37
- if (typeof path === 'string') {
38
- if (re.rfc398622.test(path)) {
39
- throw new Error('Invalid character in path naming');
40
- }
41
-
42
- this.path = path;
43
- }
44
- else if (path instanceof RegExp) {
45
- const re = path.toString().slice(1, -1);
46
-
47
- if (re[0] === '^') {
48
- throw new Error(
49
- `The use of the anchor '^' at the beginning ` +
50
- `of the path is not allowed`
51
- );
52
- }
53
-
54
- if (re[re.length - 1] === '$') {
55
- throw new Error(
56
- `The use of the anchor '$' at the ending ` +
57
- `of the path is not allowed`
58
- );
59
- }
60
-
61
- this.pattern = new RegExp(`^${re}$`);
62
- }
63
- else {
64
- throw new Error(
65
- `Invalid option 'path'. Expected 'string' or RegExp object`
66
- );
67
- }
68
-
69
- this.method = method.toLowerCase();
70
- this.handler = handler;
71
- this.finish = finish;
72
- this.childs = [];
73
- }
74
-
75
- route(options) {
76
- const route = new Route(options);
77
- this.childs.push(route);
78
-
79
- return route;
80
- }
81
-
82
- find(paths, index = 0) {
83
- const path = paths[index];
84
- const found = this.pattern === undefined ?
85
- this.path === path : this.pattern.test(path);
86
-
87
- if (found === false) {
88
- return null;
89
- }
90
-
91
- index++;
92
-
93
- if (paths.length === index || this.finish === true) {
94
- return this;
95
- }
96
-
97
- for (let i of this.childs) {
98
- const route = i.find(paths, index);
99
-
100
- if (route !== null) {
101
- return route;
102
- }
103
- }
104
-
105
- return null;
106
- }
107
- }
108
-
109
- module.exports = Route;