# finger

> Urls matching&building like a boss

Latest version **2.1.1** (published 2015-06-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install finger
pnpm add finger
yarn add finger
bun add finger
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.1.1 |
| Published | 2015-06-24 |
| First published | 2014-06-03 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 4 |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Golyshev Dmitrii |
| Maintainers | golyshevd |
| Keywords | router, route, rule, pattern, url, match, build |

## Links

- npm: https://www.npmjs.com/package/finger
- Repository: https://github.com/fistlabs/finger
- Issues: https://github.com/fistlabs/finger/issues
- npm.io page: https://npm.io/package/finger

## Dependencies (4)

- [regesc](https://npm.io/package/regesc.md) 0.0.1
- [methods](https://npm.io/package/methods.md) 1.1.1
- [unique-id](https://npm.io/package/unique-id.md) 0.0.1
- [lodash-node](https://npm.io/package/lodash-node.md) 3.5.0

## Alternatives

- [express-promise-router](https://npm.io/package/express-promise-router.md) — 736.1K weekly downloads
- [next-usequerystate](https://npm.io/package/next-usequerystate.md) — 29.8K weekly downloads
- [@bitkyc08/opencodex](https://npm.io/package/@bitkyc08/opencodex.md) — 4.6K weekly downloads
- [lynkr](https://npm.io/package/lynkr.md) — 575 weekly downloads
- [baremetal.js](https://npm.io/package/baremetal.js.md) — 42 weekly downloads

## Recent versions

- 2.1.1 (latest) — 2015-06-24
- 2.1.0 — 2015-03-18
- 2.0.0 — 2015-03-01
- 1.3.2 — 2015-01-30
- 1.3.1 — 2015-01-15
- 1.3.0 — 2015-01-12
- 1.2.0 — 2015-01-12
- 1.1.0 — 2015-01-12
- 1.0.0 — 2014-12-23
- 1.0.0-4 — 2014-11-05
- 1.0.0-3 — 2014-11-05
- 1.0.0-2 — 2014-11-05
- 1.0.0-1 — 2014-11-05
- 1.0.0-0 — 2014-11-05
- 0.3.0 — 2014-07-18
- … 8 more at https://npm.io/package/finger/versions

## README

finger [![Build Status](https://travis-ci.org/fistlabs/finger.svg?branch=master)](https://travis-ci.org/fistlabs/finger)
=========

Finger is a powerful and fast nodejs router

###Rule
`Rule` is a class that can match and build urls described in special syntax.

```js
var Rule = require('finger').Rule;
```

####`Rule new Rule(String ruleString[, Object options[, Object data]])`
Creates new rule.

```js
var rule = new Rule('/');
```

#####`String ruleString`

`ruleString` is a string that consists of pathname description nad optional query string description

######Pathname description

Pathname rule is a string that should describe url.

```
/news/
```

Pathname rule may include parameters.

```
/news/<postId>
```

The rule above both valid for any url that starts with `/news/` and ends with any character sequence except of `/`.

Parameters can have a type.

```
/news/<Number:postId>
```

`Number` is a type of `postId` parameter. It is a named type. `Number` type is included in set of [builtin common types](/core/common-types.js).

Types may also be anonymous.

```
/news/<{\\d+}:postId>
```

Regular expression may be passed between the `{}`. Parameter are for retrieving values while matching and passing while building urls.

Pathname consists of required and optional parts.

```
/news/(<postId>/)
```

In the rule above `postId` parameter including trailing `/` is optional. The rule both valid for `/news/` and `/news/42/` urls.

######Query description

Query description is a sequence of query parameters rules. Query parameter may be required or optional.

```
/news&postId?rnd
```

The rule above describes `/news/` pathname with any query, but `postId` parameter is required. `/news?postId=42` is valid, but `/news` is invalid. `rnd` parameter is optional.

Any query parameter may also have a type.

```
/news/&Number:postId
```

One parameter rule describes one parameter by default. But parameter rules may be multiple.

```
/news/?Number:tag+
```

The rule above describes news feed, that can be filtered by tags.

#####`Object options`
Rule object support some options

######`Boolean options.ignoreCase`
Disables case sensitivity for pathname rule

```js
var rule = new Rule('/news/', {
    ignoreCase: true
});
```

For this rule both `/news/` and `/NeWs/` urls are identical.

######`Boolean options.appendSlash`
Allows url to do not contain trailing slash

```js
var rule = new Rule('/news/', {
    appendSlash: true
});
```

For this rule both `/news/` and `/news` urls are valid.

######`String options.queryEq`
A character which separates query argument name and value. Defaults to `'='`.

```js
var rule = new Rule('/', {
    queryEq: ':'
});
rule.match('/?foo:bar'); // -> {foo: 'bar'}
```

######`String options.querySep`
A character which separates query arguments. Defaults to `'&'`.

```js
var rule = new Rule('/', {
    querySep: ','
});
rule.match('/?foo=bar,bar=baz'); // -> {foo: 'bar', bar: 'baz'}
```

######`String options.basePath`
Base urls path.

```js
var rule = new Rule('/news/', {
    basePath: '/site/'
});
rule.match('/news/'); // -> null
rule.match('/site/news/'); // -> {}
rule.build(); // -> /site/news/
```

#####`Object data`
The data will be appended to rule

```js
var rule = new Rule('/news/', {
    appendSlash: true
}, {
    name: 'news'
});
```

####`Object|null rule.match(String url)`
Matches the url to the rule. Returns the set of values according to described arguments

```js
var rule = new Rule('/news/(<postId>/)');
rule.match('/news/'); // -> {postId: undefined}
rule.match('/news/146/?date=42'); // -> {postId: '146', date: '42'}
rule.match('/forum/'); // -> null
```

####`String rule.build([Object args])`
Builds url from rule

```js
var rule = new Rule('/news/(<postId>/)');

rule.build(); // -> '/news/'
rule.build({postId: 146}); // -> '/news/146/'
rule.build({date: 42}); // -> /news/?date=42
rule.build({postId: 146, date: 42}); // -> /news/146/?date=42
```

###Matcher

`Matcher` is a set of rules that gives an interface to manage rules e.g. adding, deleting, matching.

```js
var Matcher = require('finger').Matcher;
```

####`Matcher new Matcher([Object options])`
Creates new `matcher` object. `options` is a general options for all rules.

####`Rule matcher.addRule(String ruleString[, Object data])`
Adds a ```rule``` to `matcher`.
`ruleString` is a rule declaration that I mentioned above.
`data` is an object that will be associated with rule. `data.name` is required, it will be random generated if omitted.

```js
var matcher = new Matcher();
var rule = matcher.addRule('/', {name: 'index', foo: 42});
rule.data.name // -> 'index'
rule.data.foo // -> 42
```

####`Rule|null matcher.delRule(String name)`
Deletes the rule from set

```js
var matcher = new Matcher();
var rule = matcher.addRule('/', {name: 'index'});
assert.strictEqual(rule, matcher.delRule('index'));
```

####`Rule|void matcher.getRule(String name)`
Returns the `rule` by `name`

```js
var matcher = new Matcher();
var rule = matcher.addRule('/', {name: 'index'});
assert.strictEqual(rule, matcher.getRule('index'));
```

####`Array<Object> matcher.findMatches(String url)`
Returns all match results

```js
var matcher = new Matcher();
matcher.addRule('/news/', {name: 'news'})
matcher.addRule('/<page>/', {name: 'other'});
assert.deepEqual(matcher.matchAll('/news/'), [
    {
        name: 'news', 
        args: {}
    }, 
    {
        name: 'other', 
        args: {
            page: 'news'
        }
    }
]);
```

####`Matcher matcher.setBasePath(String basePath)`
Set basePath to all existing rules. Also basePath will be applied to all new rules.

```js
var matcher = new Matcher();
matcher.addRule('/news/', {name: 'news'});
matcher.findMatches('/site/news/'); // -> []
matcher.setBasePath('/site/');
matcher.findMatches('/site/news/'); // -> [{name: 'news', args: {}}]
```

###Router

`Router` is a subclass of `Matcher`.

```js
var Router = require('finger');
```

`Router` is a `Matcher` that optimized and improved to match http requests.

`Router`'s rules had extended rule string. `Router`'s rules may describe not only url, but also request method and some options.

```
POST,PUT /upload/ si
```

That means that the should match url only if request method are `POST` or `PUT`. Also two last characters at the and of rule means that rule should ignore case and append slash to url. Flags in lower letter case enables options, but in upper, disables.

If method does not specified, that `GET` should be implicitly added. Special value for method is `*`. `*` means that any method will be matched.

####`Array<String> router.findVerbs(String url)`

Find all methods that allowed for passed url.

####`Array<Rule> router.getAllowedRules(String verb)`

Returns all rules that allowed for passed verb.

####`Array<Match> router.findMatchesFor(String url, Array<Rule>)`

Returns all matches for passed url and rules.

###Common usage

```js
var matches = router.getAllowedMatches(req.method, req.url);
if (!matches.length) {
    res.statusCode = 404;
    res.end();
    return;
}
doSomethingWithMatches(matches);
```

###Advanced usage

```js
// Get all rules that potentially may handle request
var allowedRules = router.getAllowedRules(req.method);
if (!allowedRules.length) {
    // The method is not implemented
    res.statusCode = 501;
    res.end();
    return;
}
// Find all matched
var matches = router.findMatchesFor(req.url, allowedRules);
if (!matches.length) {
    // No matches found. Maybe incorrect request method
    var allowedVerbs = router.findVerbs(req.url);
    if (!allowedVerbs.length) {
        // No any handlers. Document Not Found
        res.statusCode = 404;
        res.end();
        return;
    }    
    // Found other rules, that can handle the request
    res.setHeader('Allow', allowedVerbs.join(','));
    // Method Not Allowed
    res.statusCode = 405;
    res.end();
    return;
}
// Score!
doSomethingWithMatches(matches);
```

---------
LICENSE [MIT](LICENSE)

---
_Source: https://npm.io/package/finger · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
