alasym

0.0.8 • Public • Published

alasym

It is a tool for routing a la symfony (PHP framework). Alasym is able to parse your routing.yml and match route for URL. At this time the code works only on Node.js environment.

This module is not a copy of symfony routing, just has a similar syntax. It supports methods, parameters (including regular expressions for ones), default values and one option.

The module has only four methods.

loadConfig(filePathˢᵗʳ)

This method returns a promise, loads file and calls parseConfigᶠᵘⁿᶜ. Resolve gets routesᵒᵇʲ - an object, containing parsed routes.

returns promiseᴬ⁺

parseConfig(configContentˢᵗʳ)

This one returns a promise, just parses a content and then passes to function resolve an object routesᵒᵇʲ, which is parsed routing-config. Remember, that the content should be written in yaml-compatible syntax.

returns promiseᴬ⁺

matchURL(routesᵒᵇʲ, urlˢᵗʳ, methodˢᵗʳ)

It is the most interesting function, which matches current urlˢᵗʳ and methodˢᵗʳ with already parsed config. It returns an object of a route or null (if nothing is matched). Method is optional parameter, by default it is equal GET.

returns routeᵒᵇʲ or null⁰

generateURL(routeᵒᵇʲ, paramsᵒᵇʲ)

Returns URL, which is generated using paramsᵒᵇʲ and which satisfies route's pattern. Remember, that the first argument is an object, but not a string. If required parameter is missing in paramsᵒᵇʲ, then empty string is used.

returns urlˢᵗʳ

Example

There is one exhaustive example below:

# routing.yml 
root:
    url: /
    method: GET
    destination: # destination could be any object or string 
        handler: rootHandler
        data: 123
 
page:
    url: /page/:pageName
    method: GET # by default GET 
    params:
        pageName: /\w+/
    defaults:
        pageName: welcome
    options:
        caseSensitive: true # by default false 
    destination:
        handler: pageHandler
// index.js
'use strict';
let alasym = require('alasym');
alasym.loadConfig('routing.yml')
    .then(routes => {
        let route = alasym.matchURL(routes, '/page/about', 'GET');
        console.log('Matched route is:', route);
        /* {
            name: 'page',
            url: '/page/about',
            method: 'GET',
            matches: {pageName: 'about'},
            destination: {handler: 'pageHandler'},
            options: {caseSensitive: true}
        } */
 
        route = alasym.matchURL(routes, '/path/to/void'); // null
    })
    .catch(error => {
        console.error('Something has gone wrong!', error);
    });

And here is an another example, how to use alasym in a real project.

Package Sidebar

Install

npm i alasym

Weekly Downloads

1

Version

0.0.8

License

GPL-3.0

Last publish

Collaborators

  • enet