Coder Social home page Coder Social logo

susanin's People

Contributors

doochik avatar isqua avatar miripiruni avatar myshov avatar ruslankerimov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

susanin's Issues

Conditions syntax to allow multiple parameter values or not

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" ]
}

Add custom matchers

Привет! Я уже решил свою проблему, но меня просто тогда смутила один момент в коде, строки 432-438, там все свойства переданные в match кроме path, строго сравниваются со свойствами в data, и это не очень удобно, хочетелось бы уметь для таких свойст задавать смециальные функции сравнения. Например у нас в проекте есть несколько роутов которые только на домене official.* и там удобно в data оставить host: /^official./ а в match передать просто { path: '/my/path/', host: "my.host"}, предварительно настроив роут так, чтобы свойство host он сравнивал с помощью функции сравнения. Я именно так у себя и сделал, изготовив небольшую обертку над susanin, но удивился что этого нет "в коробке". То есть хотелось бы уметь задавать кастомные матчеры, не только для path, а еще и свои добавлять..

Default values

  1. Why I must specify data.directory for controllers each time?
  2. Same for data.action.
  3. I want have GET method by default.

Very-very special "query_string"

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" ]
}

conditions doesn't applies while building url

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.

Allow chaining of Router.addRoute() calls

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..

Removing duplicate slashes

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

Missed ',' in README

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}'
    }
});

Не строится url, если первый опциональный параметр совпал со своим значением по-умолчанию.

Для опциональной части роута проверяется, что параметры, от которых она зависит, не совпадают с дефолтными значениями и если это так - вся часть не выводится.
Нужно дописать проверку на случай вложенных частей.

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 == '/'

Matched from path parameters overrides values passed via query string

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 repo dispatch old version of lib

$ 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.

Router doesn't check query string values to satisfy conditions

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" ]
}

Invalid arguments matching in the URLs which contains double slash in the middle

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.

Зачем парсятся GET параметры из урла?

Они на самом деле мешают и вообще они мне не нужны в параметрах роутера. А если и будут нужны, то можно использовать другой модуль для их парсинга, например connect-query. Вообщем мне не нравится идея, что параметры GET и роутера смешаны. Хочется явно брать параметры из GET, POST или URL (susanin).

  1. Хотелось бы иметь возможность получить имя паттерна по которому был найден модуль, сейчас он лежит приватно тут — _options.pattern и вдобавок он какой-то грязный (всякие скобочки и т.п)

Create method "filter"

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.

Поддержка нескольких роутов с одинаковым именем

У меня есть страница поиска, у которой урлы довольно заковыристые. И одним регэкспом не выражаются.
Если я их под разными именами добавлю, то не смогу потом строить урлы, т.к. мне нужно будет знать, а с какое имя подходит к этому набору параметров.
А если под одним, то, очевидно, сохранится только последний.

А неплохо бы сохранять все, а при построении урла выбирать тот, к которому подходят переданные параметры.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.