nodules / susanin Goto Github PK
View Code? Open in Web Editor NEWJavaScript router system
License: Other
JavaScript router system
License: Other
For default router replacement.
Now Susanin always accept multiple values for parameter from query string, but always use last parameter with the same name from the path.
Route definition:
{
pattern: '/(<part>)(/<part>)'
}
Result for /one/two
is:
{
"part": "two"
}
Result for /?part=one&part=two
is:
{
"part": [ "one", "two" ]
}
And integrate with travis-ci
Привет! Я уже решил свою проблему, но меня просто тогда смутила один момент в коде, строки 432-438, там все свойства переданные в match кроме path, строго сравниваются со свойствами в data, и это не очень удобно, хочетелось бы уметь для таких свойст задавать смециальные функции сравнения. Например у нас в проекте есть несколько роутов которые только на домене official.* и там удобно в data оставить host: /^official./ а в match передать просто { path: '/my/path/', host: "my.host"}, предварительно настроив роут так, чтобы свойство host он сравнивал с помощью функции сравнения. Я именно так у себя и сделал, изготовив небольшую обертку над susanin, но удивился что этого нет "в коробке". То есть хотелось бы уметь задавать кастомные матчеры, не только для path, а еще и свои добавлять..
data.directory
for controllers each time?data.action
.And will have to increase major version, because changing isn't backward compatible
Parameter query_string
cann't be used, because Susanin use this name to address query string part of the URL.
Route definition:
{
pattern: '/test/<query_string>/<x>'
}
Result for URL /test/xxx/v
is:
{
"x": "v",
"xxx": ""
}
And finish him with the /test/xxx=1&xxx=3/v
!
{
"x": "v",
"xxx": [ "1", "3" ]
}
configuration from demo page:
{
pattern: '/jeans(/<brand>(/<id>))',
conditions: {
brand: [ 'levis', 'wrangler' ],
id: '\\d{3,5}'
},
defaults: {
brand: 'levis',
}
}
Build params:
{
brand: 'noname'
}
Result:
/jeans/noname
but result isn't acceptable for this route.
Existing interface is a bit annoying when writing new router:
router.addRoute({
...
});
router.addRoute({
...
});
// +100500 route.addRoute calls
I suppose to return router instance from addRoute
to allow chaining:
router
.addRoute({
...
})
.addRoute({
...
});
Only a bit of sugar, no anything more..
According to basic principals of URL normalization, duplicate slashes must be removed. If we don't want modify source URL, duplicate slashed must be ignored.
Examples:
http://www.яндекс.рф/////index.php
http://www.яндекс.рф///index////subdir////
http://www.яндекс.рф///index//..//../subfile
Expected output:
http://www.яндекс.рф/index.php
http://www.яндекс.рф/index/subdir/
http://www.яндекс.рф/index/subfile
From log:
silly gunzTarPerm extractEntry test/tests/router.find_.js
error Error : ENOENT, open .....\router.find_.js
var route = Susanin.Route({
pattern : '/products(/<category>(/<id>))(/)',
defaults : {
category : 'shoes',
id : '123'
},
conditions : {
category : [ 'shoes', 'jeans', 'shirt' ] //need ',' symbol here !
id : '\\d{3,4}'
}
});
var susanin = require('./routes'),
found = susanin.findFirst(req.url);
if (found !== null) {
console.log(Array.isArray(found)); // true
}
Сейчас конструктор Route
мутирует входной объект options
(а именно, дописывает поле pattern
):
https://github.com/nodules/susanin/blob/1.0.3/lib/route.js#L164
В старых версиях такого не было:
https://github.com/nodules/susanin/blob/0.1.11/susanin.js#L197
Correct badge path is https://travis-ci.org/nodules/susanin.png?branch=master
Для опциональной части роута проверяется, что параметры, от которых она зависит, не совпадают с дефолтными значениями и если это так - вся часть не выводится.
Нужно дописать проверку на случай вложенных частей.
var route = Susanin.Route({
name: 'index',
pattern: '/(<sect>/(<subsect>/(<subsubsect>/)))',
defaults: {
sect: 'my-sect'
},
data: {
controller: 'index'
}
});
var url = route.build({ sect: 'my-sect', subsect: 'test' });
Ожидаем: url == '/my-sect/test/'
Фактически: url == '/'
Route definition:
{
pattern: '/jeans(/<brand>(/<id>))',
conditions: {
brand: [ 'levis', 'wrangler' ],
id: '\\d{3,5}'
},
defaults: {
brand: 'levis'
}
}
Result for URL '/jeans/levis?id=567&id=678'
:
{
"brand": "levis",
"id": [ "567", "678" ]
}
but result for URL '/jeans/levis/456?id=567&id=678'
looks incorrect (query string values overridden by matched from path, instead of be extended):
{
"brand": "levis",
"id": "456"
}
$ bower info susanin
bower cached git://github.com/nodules/susanin.git#0.1.9
It will be great to update bower.json
and pass correct lib version to it. Unfortunatelly, I can't understand branches policy in this repo to make pull request.
Route definition:
{
pattern: '/jeans(/<brand>(/<id>))',
conditions: {
brand: [ 'levis', 'wrangler' ],
id: '\\d{3,5}'
},
defaults: {
brand: 'levis'
}
});
Result for URL /jeans?brand=wrangler
is:
{
"brand": "levis"
}
Route definition:
{
pattern: '/jeans(/<brand>(/<id>))',
conditions: {
brand: [ 'levis', 'wrangler' ],
id: '\\d{3,5}'
},
defaults: {
brand: 'levis'
}
}
Values for the parameter id
is accepted from the URL '/jeans/levis?id=5&id=6'
:
{
"brand": "levis",
"id": [ "5", "6" ]
}
Route options:
{
pattern: '/issues(/<id>(/<action>(/<sub_id>)))',
conditions: {
id: '\\D[\\d\\w]+\\-\\d+',
sub_id: '[\\dA-Fa-f]+',
action: '\\D[\\d\\w]*'
}
}
Test urls:
/issues/NODULES-154/a/daf675 -> ok
/issues//NODULES-154/a/daf675 -> invalid id: '/NODULES-154'
/issues/NODULES-154//a/daf675 -> invalid action: '/a'
/issues/NODULES-154/a//daf675 -> ok, null
/issues/NODULES-154///a/daf675 -> ok, null
I expect null
as result of matching for the second and 3rd URLs or treating multiple consecutive slashes as one, but test results look wrong.
Они на самом деле мешают и вообще они мне не нужны в параметрах роутера. А если и будут нужны, то можно использовать другой модуль для их парсинга, например connect-query. Вообщем мне не нравится идея, что параметры GET и роутера смешаны. Хочется явно брать параметры из GET, POST или URL (susanin).
We need to have a method like this:
var router = new Susanin();
router
.addRoute({
name : 'offers',
pattern : '/<mark>/<model>/<configuration_id>/<controller>(/)',
conditions : {
controller : [ 'offers', 'articles', 'stats' ],
configuration_id : '\\d+'
},
filter : function(params) {
// Here we can change params, for example:
params.controller === 'stats' && (params.controller = 'statistics');
// Also we can rename param`s name:
params.conf_id = params.configuraion_id;
delete params.configuraion_id;
}
});
It will help to write less routes and support old link`s addresses.
Hello!
international letter chars are not supported -
var Route = require('susanin').Route;
var route = Route('/<foo>/<bar>/<baz>');
console.log(route.match('/esc/rzy/aie')); // { foo: 'esc', bar: 'rzy', baz: 'aie' }
console.log(route.match('/ěšč/řžý/áíé')); // null
Using xregexp library (its unicode support - http://xregexp.com/plugins/#unicode) seems to be possible workaround.
У меня есть страница поиска, у которой урлы довольно заковыристые. И одним регэкспом не выражаются.
Если я их под разными именами добавлю, то не смогу потом строить урлы, т.к. мне нужно будет знать, а с какое имя подходит к этому набору параметров.
А если под одним, то, очевидно, сохранится только последний.
А неплохо бы сохранять все, а при построении урла выбирать тот, к которому подходят переданные параметры.
Because a default array value will be passed to the result via reference, not copied.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.