vanilla-jet 1.0.4 → 1.0.5

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.
Files changed (2) hide show
  1. package/framework/router.js +163 -194
  2. package/package.json +1 -1
@@ -1,103 +1,69 @@
1
- /**
2
- Version 3.5
3
- Created by: nalancer08 <https://github.com/nalancer08>
4
- **/
5
-
6
- var Request = require('./request.js');
7
- var Response = require('./response.js');
8
- var _ = require('underscore');
9
-
10
- function Router(server) {
11
-
12
- this.routes = {
13
- '*': [],
14
- 'get': [],
15
- 'post': []
16
- };
17
- this.defaultRoute = '';
18
- this.server = server;
19
- this.cwd = process.cwd();
20
- }
1
+ let Request = require('./request.js');
2
+ let Response = require('./response.js');
3
+ let _ = require('underscore');
21
4
 
22
- Router.prototype.routeToRegExp = function(route) {
23
-
24
- var optionalParam = /\((.*?)\)/g,
25
- namedParam = /(\(\?)?:\w+/g,
26
- splatParam = /\*\w+/g,
27
- escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
28
- // Convert route to regular expression, this was taken from Backbone's router
29
- route = route.replace(escapeRegExp, '\\$&')
30
- .replace(optionalParam, '(?:$1)?')
31
- .replace(namedParam, function(match, optional) {
32
- return optional ? match : '([^/?]+)';
33
- })
34
- .replace(splatParam, '([^?]*?)');
35
- return new RegExp(`^${route}(?:\\?([\\s\\S]*))?$`);
36
- };
37
-
38
- Router.prototype.addRoute = function(method, route, handler, insert) {
39
-
40
- var obj = this,
41
- insert = insert || false,
42
- method = method.toLowerCase(),
43
- prev = (obj.server.options.base_url && obj.server.options.base_url != '' && obj.server.options.base_url != '/') ? obj.server.options.base_url : '',
44
- instance = {
45
- regexp: obj.routeToRegExp(prev + route),
46
- handler: handler
5
+ class Router {
6
+
7
+ constructor(server) {
8
+
9
+ this.routes = {
10
+ '*': [],
11
+ 'get': [],
12
+ 'post': []
47
13
  };
48
- // Add the route, may be at the beginning or at the end
49
- if (insert) { // Adding the route at the beginning of the route's array
50
- obj.routes[method].unshift(instance);
51
- } else { // Adding the route at the end of the route's array
52
- obj.routes[method].push(instance);
14
+ this.defaultRoute = '';
15
+ this.server = server;
16
+ this.cwd = process.cwd();
53
17
  }
54
- };
55
-
56
- Router.prototype.removeRoute = function(method, route) {};
57
18
 
58
- Router.prototype.onRequest = function(req, res) {
19
+ routeToRegExp(route) {
20
+
21
+ var optionalParam = /\((.*?)\)/g, namedParam = /(\(\?)?:\w+/g, splatParam = /\*\w+/g, escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
22
+ // Convert route to regular expression, this was taken from Backbone's router
23
+ route = route.replace(escapeRegExp, '\\$&')
24
+ .replace(optionalParam, '(?:$1)?')
25
+ .replace(namedParam, function (match, optional) {
26
+ return optional ? match : '([^/?]+)';
27
+ })
28
+ .replace(splatParam, '([^?]*?)');
29
+ return new RegExp(`^${route}(?:\\?([\\s\\S]*))?$`);
30
+ }
59
31
 
60
- let obj = this;
61
- let isMatch = false;
62
- let zlib = require('zlib');
63
- let response = new Response(res);
64
- let request = new Request(req, {
65
- onDataReceived: function() {
32
+ addRoute(method, route, handler, insert) {
66
33
 
67
- console.log(request.path);
68
- if (request.path == obj.server.options.base_url) {
69
- request.path = obj.server.options.base_url + obj.defaultRoute;
70
- }
71
- console.log(request.path);
34
+ var obj = this, insert = insert || false, method = method.toLowerCase(), prev = (obj.server.options.base_url && obj.server.options.base_url != '' && obj.server.options.base_url != '/') ? obj.server.options.base_url : '', instance = {
35
+ regexp: obj.routeToRegExp(prev + route),
36
+ handler: handler
37
+ };
38
+ // Add the route, may be at the beginning or at the end
39
+ if (insert) { // Adding the route at the beginning of the route's array
40
+ obj.routes[method].unshift(instance);
41
+ } else { // Adding the route at the end of the route's array
42
+ obj.routes[method].push(instance);
43
+ }
44
+ }
72
45
 
73
- // Try with the routes for the current method (get or post)
74
- _.each(obj.routes[request.type], function(route) {
75
- if ( request.path.match(route.regexp) ) {
46
+ removeRoute(method, route) {}
76
47
 
77
- var parts = route.handler.split('.'),
78
- clazz = parts[0],
79
- method = parts[1],
80
- callback = obj.validateCallback(clazz, method);
48
+ onRequest(req, res) {
81
49
 
82
- if (callback && callback != undefined && callback != '') {
50
+ let obj = this;
51
+ let isMatch = false;
52
+ let zlib = require('zlib');
53
+ let response = new Response(res);
54
+ let request = new Request(req, {
55
+ onDataReceived: function () {
83
56
 
84
- isMatch = true;
85
- handled = callback(request, response, obj.server);
86
- return;
87
- }
57
+ //console.log(request.path);
58
+ if (request.path == obj.server.options.base_url) {
59
+ request.path = obj.server.options.base_url + obj.defaultRoute;
88
60
  }
89
- });
90
-
91
- // If not handled yet, try with the wildcard ones
92
- if (!handled) {
93
- _.each(obj.routes['*'], function(route) {
61
+ //console.log(request.path);
62
+ // Try with the routes for the current method (get or post)
63
+ _.each(obj.routes[request.type], function (route) {
64
+ if (request.path.match(route.regexp)) {
94
65
 
95
- if ( request.path.match(route.regexp) ) {
96
-
97
- var parts = route.handler.split('.'),
98
- clazz = parts[0],
99
- method = parts[1],
100
- callback = obj.validateCallback(clazz, method);
66
+ var parts = route.handler.split('.'), clazz = parts[0], method = parts[1], callback = obj.validateCallback(clazz, method);
101
67
 
102
68
  if (callback && callback != undefined && callback != '') {
103
69
 
@@ -107,136 +73,139 @@ Router.prototype.onRequest = function(req, res) {
107
73
  }
108
74
  }
109
75
  });
110
- }
111
76
 
112
- // No route catched, maybe it's a static content
113
- // or not handled? Well, at this point we call 404
114
- if (handled == false && isMatch == false ) {
115
-
116
- var path = require('path'),
117
- ext = path.extname(req.url).replace('.', ''),
118
- extHandled = false,
119
- extHeader = {};
120
- var mimes = {
121
-
122
- 'png' : 'image/png',
123
- 'webp': 'image/webp',
124
- 'jpg' : 'image/jpg',
125
- 'css' : 'text/css',
126
- 'gz' : 'application/x-gzip',
127
- 'gif' : 'image/gif',
128
- 'js' : 'text/javascript',
129
- 'svg' : 'image/svg+xml',
130
- 'ttf' : 'application/x-font-ttf',
131
- 'otf' : 'application/x-font-opentype',
132
- 'pdf' : 'application/pdf',
133
- 'json' : 'application/json'
134
- };
135
-
136
- var compressionMimes = {
137
- 'css' : 'text/css',
138
- 'js' : 'text/javascript',
139
- 'gz' : 'application/x-gzip'
140
- };
141
-
142
- if (mimes[ext] != undefined && mimes[ext] != 'undefined') {
143
-
144
- extHandled = true;
145
- extHeader = {'Content-Type': mimes[ext]};
146
- }
77
+ // If not handled yet, try with the wildcard ones
78
+ if (!handled) {
79
+ _.each(obj.routes['*'], function (route) {
147
80
 
148
- if (extHandled) {
149
-
150
- let fs = require('fs'),
151
- rep = obj.cwd.replace('core/framework', ''),
152
- route = request.path.replace(obj.server.options.base_url, ''),
153
- filename = path.join(rep, route),
154
- filePrivate = obj.isProtectedFile(route);
155
-
156
- console.log(rep);
157
- console.log(route);
158
- console.log(filename);
159
- console.log("-------------");
160
-
161
- fs.exists(filename, function(exists) {
162
-
163
- if (exists && !filePrivate) {
164
-
165
- var acceptEncoding = (req.headers['accept-encoding'] != undefined) ? req.headers['accept-encoding'] : '';
166
- var fileStream = fs.createReadStream(filename);
167
- if (acceptEncoding.match(/\bgzip\b/) && compressionMimes[ext] != undefined) {
168
- extHeader['Content-Encoding'] = 'gzip';
169
- res.writeHead(200, extHeader);
170
- fileStream.pipe(zlib.createGzip()).pipe(res);
171
- } else {
172
- res.writeHead(200, extHeader);
173
- fileStream.pipe(res);
174
- }
175
- return;
81
+ if (request.path.match(route.regexp)) {
176
82
 
177
- } else {
83
+ var parts = route.handler.split('.'), clazz = parts[0], method = parts[1], callback = obj.validateCallback(clazz, method);
178
84
 
179
- // Return 404
180
- obj.onNotFound(response);
85
+ if (callback && callback != undefined && callback != '') {
86
+
87
+ isMatch = true;
88
+ handled = callback(request, response, obj.server);
89
+ return;
90
+ }
181
91
  }
182
92
  });
183
93
  }
94
+
95
+ // No route catched, maybe it's a static content
96
+ // or not handled? Well, at this point we call 404
97
+ if (handled == false && isMatch == false) {
98
+
99
+ var path = require('path'), ext = path.extname(req.url).replace('.', ''), extHandled = false, extHeader = {};
100
+ var mimes = {
101
+ 'png': 'image/png',
102
+ 'webp': 'image/webp',
103
+ 'jpg': 'image/jpg',
104
+ 'css': 'text/css',
105
+ 'gz': 'application/x-gzip',
106
+ 'gif': 'image/gif',
107
+ 'js': 'text/javascript',
108
+ 'svg': 'image/svg+xml',
109
+ 'ttf': 'application/x-font-ttf',
110
+ 'otf': 'application/x-font-opentype',
111
+ 'pdf': 'application/pdf',
112
+ 'json': 'application/json'
113
+ };
114
+
115
+ var compressionMimes = {
116
+ 'css': 'text/css',
117
+ 'js': 'text/javascript',
118
+ 'gz': 'application/x-gzip'
119
+ };
120
+
121
+ if (mimes[ext] != undefined && mimes[ext] != 'undefined') {
122
+
123
+ extHandled = true;
124
+ extHeader = { 'Content-Type': mimes[ext] };
125
+ }
126
+
127
+ if (extHandled) {
128
+
129
+ let fs = require('fs'), rep = obj.cwd.replace('core/framework', ''), route = request.path.replace(obj.server.options.base_url, ''), filename = path.join(rep, route), filePrivate = obj.isProtectedFile(route);
130
+
131
+ fs.exists(filename, function (exists) {
132
+
133
+ if (exists && !filePrivate) {
134
+
135
+ var acceptEncoding = (req.headers['accept-encoding'] != undefined) ? req.headers['accept-encoding'] : '';
136
+ var fileStream = fs.createReadStream(filename);
137
+ if (acceptEncoding.match(/\bgzip\b/) && compressionMimes[ext] != undefined) {
138
+ extHeader['Content-Encoding'] = 'gzip';
139
+ res.writeHead(200, extHeader);
140
+ fileStream.pipe(zlib.createGzip()).pipe(res);
141
+ } else {
142
+ res.writeHead(200, extHeader);
143
+ fileStream.pipe(res);
144
+ }
145
+ return;
146
+
147
+ } else {
148
+
149
+ // Return 404
150
+ obj.onNotFound(response);
151
+ }
152
+ });
153
+ }
154
+ }
184
155
  }
185
- }
186
- }),
187
- handled = false;
188
- isMatch = false;
189
- };
156
+ }), handled = false;
157
+ isMatch = false;
158
+ }
190
159
 
191
- Router.prototype.isProtectedFile = function(route) {
160
+ isProtectedFile(route) {
192
161
 
193
- let protectedDirs = ['framework', 'external', 'node_mudules'];
194
- var routeParts = route.split('/');
195
- if (routeParts[1] != undefined && routeParts.length > 2) {
196
- return protectedDirs.includes(routeParts[1]);
162
+ let protectedDirs = ['framework', 'external', 'node_mudules'];
163
+ var routeParts = route.split('/');
164
+ if (routeParts[1] != undefined && routeParts.length > 2) {
165
+ return protectedDirs.includes(routeParts[1]);
166
+ }
167
+ return true;
197
168
  }
198
- return true;
199
- };
200
169
 
201
- Router.prototype.validateExtension = function(route) {};
170
+ validateExtension(route) {}
202
171
 
203
- Router.prototype.validateCallback = function(clazz, method) {
172
+ validateCallback(clazz, method) {
204
173
 
205
- var obj = this,
206
- endpoints = obj.server.functions.endpoints;
174
+ var obj = this, endpoints = obj.server.functions.endpoints;
207
175
 
208
- if (endpoints[clazz] != undefined) {
176
+ if (endpoints[clazz] != undefined) {
209
177
 
210
- clazz = endpoints[clazz];
178
+ clazz = endpoints[clazz];
211
179
 
212
- if (typeof clazz[method] === 'function') {
213
- return clazz[method];
180
+ if (typeof clazz[method] === 'function') {
181
+ return clazz[method];
182
+ }
214
183
  }
184
+ return '';
215
185
  }
216
- return '';
217
- };
218
- /**
219
- * This method allows to set the default route for the api
220
- * @param route: String name for the route
221
- **/
222
- Router.prototype.setDefaultRoute = function(route) {
223
186
 
224
- var obj = this;
225
- obj.defaultRoute = route;
226
- };
187
+ /**
188
+ * This method allows to set the default route for the api
189
+ * @param route: String name for the route
190
+ **/
191
+ setDefaultRoute(route) {
227
192
 
228
- Router.prototype.getDefaultRoute = function() {
193
+ var obj = this;
194
+ obj.defaultRoute = route;
195
+ }
196
+
197
+ getDefaultRoute() {
229
198
 
230
- var obj = this,
231
- prev = (obj.server.options.base_url && obj.server.options.base_url != '' && obj.server.options.base_url != '/') ? obj.server.options.base_url : '';
199
+ var obj = this, prev = (obj.server.options.base_url && obj.server.options.base_url != '' && obj.server.options.base_url != '/') ? obj.server.options.base_url : '';
232
200
 
233
- return (prev + obj.defaultRoute);
234
- };
201
+ return (prev + obj.defaultRoute);
202
+ }
235
203
 
236
- Router.prototype.onNotFound = function(response) {
204
+ onNotFound(response) {
237
205
 
238
- response.setStatus(404);
239
- response.respond();
240
- };
206
+ response.setStatus(404);
207
+ response.respond();
208
+ }
209
+ }
241
210
 
242
211
  module.exports = Router;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vanilla-jet",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "VannilaJet framework",
5
5
  "main": "index.js",
6
6
  "scripts": {