tunnckoCore / blankr

:heart: tasks, todos, ideas, streaks, WIP, etc
https://i.am.charlike.online
4 stars 1 forks source link

dush-router npm version github tags mit license

A simple regex-based router for dush, base, minibase and anything based on them. Works on Browser and Node.js

You might also be interested in dush-no-chaining, dush-methods and dush-tap-report, a plugins for dush microscopic event emitter with simple & powerful plugin system.

<a href="https://github.com/paypal/downshift/commits?author=kentcdodds" title="Code"> :metro:

Quality 👌

By using commitizen and conventional commit messages, maintaining meaningful ChangeLog and commit history based on global conventions, following StandardJS code style through ESLint and having always up-to-date dependencies through integrations like GreenKeeper and services like David-DM this package has top quality forever.

code climate code style commitizen friendly greenkeeper friendly dependencies

Stability 💯

By following Semantic Versioning through standard-version releasing tool, this package is very stable and its tests are passing both on Windows (AppVeyor) and Linux (CircleCI) with results from 100% to 400% test coverage, reported respectively by CodeCov and nyc (istanbul).

following semver semantic releases linux build windows build code coverage nyc coverage

Support 🤝

If you have any problems, consider opening an issue or pull request with failing test proving your issue, ping me on twitter (@tunnckoCore), join the support chat room or queue a live session on CodeMentor with me. If you don't have problems, enjoy this product or using it you can donate some cash at PayPal, since this is OPEN Open Source project made with love and because some need.

tunnckoCore support code mentor paypal donate NPM monthly downloads npm total downloads

Highlights :sparkles:

Table of Contents

(TOC generated by verb using markdown-toc)

Install

Install with npm

$ npm install dush-router --save

or install using yarn

$ yarn add dush-router

Usage

For more use-cases see the tests

const dushRouter = require('dush-router')

API

router()

A plugin that adds .createRoute, .addRoute and .navigate methods for any app based on dush, base or minibase. Notice that this plugin emit events - route if match, and notFound if not route found on defined routes.

Params

Example

var dush = require('dush')
var router = require('dush-router')

var app = dush()
app.use(router())

console.log(app._routes) // => []
console.log(app.createRoute) // => function
console.log(app.addRoute) // => function
console.log(app.navigate) // => function

.addRoute

Add/register an actual route with handler to the app._routes array. It uses .createRoute method to create an "route" object that is then pushed to app._routes.

Note: If route handler returns something the app.navigate method will return that exact value on route match.

Params

Example

app.addRoute('/foobar', (context) => {
  console.log('state:', context.state) // => { hello: 'world' }
  console.log('params:', context.params) // => {}
  console.log('route:', context.route) // => '/foobar'
  console.log('pathname:', context.pathname) // => '/foobar'
})

app.navigate('/foobar', { hello: 'world' })

// or with params
app.addRoute('/user/:id', ({ state, params, route, pathname }) => {
  console.log('Hello ', state.username) // => 'Hello Charlike'
  console.log('Your ID is', params.id) // => 'Your ID is 123'

  console.log('route', route) // => '/user/:id'
  console.log('path', pathname) // => '/user/123'
})

app.navigate('/user/123', { username: 'Charlike' })

.createRoute

Just create a route with handler, same as .addRoute method, but without adding it to app._routes array. This "route" object contains .match, .regex, .route and .handler properties. Where .match is a function that accepts single argument "pathname" to check against given route, .handler is the passed handler function, .regex is the generated regex for that route string and the .route is the given route. The .match function returns null if passed "pathname" string match to the given route but not params and false if passed "pathname" not match.

Note: This method does not call the given route handler.

Params

Example

const r = app.createRoute('/user/:id', function abc (params) {
  console.log('hi user with id:', params.id)
})

console.log(r.match) // => function
console.log(r.handler) // => function
console.log(r.handler.name) // => 'abc'
console.log(r.route) // => '/user/:id'
console.log(r.regex) // => /^\/user\/(\w+)$/i

var params = r.match('/user/123')
console.log(params) // => { id: 123 }

// manually call the route handler
if (params !== false) {
  r.handler(params || {})
}

// not match, so returns `false`
params = r.match('/foobar')
console.log(params) // => false

var route = app.createRoute('/foobie', () => {})

// match, but no params, so return `null`
var res = route.match('/foobie')
console.log(res) // => null

.navigate

Manually navigate to some route with url pathname and returns what the route handler returns. You can pass a custom state which will be passed to route handler's context as context.state. This method fires notFound event when not found match, and route when find a route.

Params

Example

app.on('notFound', (context) => {
  console.log(`sorry ${context.pathname} page not exist`)
  console.log('this is incoming state:', context.state)
})
app.navigate('/foo/bar/qux', { aa: 11 })

app.addRoute('/hello/:place', (context) => {
  console.log('hi', context.params.place) // => 'hi world'
})
app.navigate('/hello/world')

// remove default "on route" handler
app.off('route')

// and define your custom one,
// to change route handler arguments
app.on('route', (handler, context) => {
  return handler(context.state, context.params)
})

// notice the handler signature, it's different than
// the default one seen in above `/hello/:place` route
app.addRoute('/user/:name', (state, params) => {
  var name = state.username || params.name

  console.log('name:', name) // => 'name: john' or 'name: charlike'

  return name
})

// it returns what the route handler return
var res = app.navigate('/user/john')
console.log(res) // => 'john', because there's no passed state

var ret = app.navigate('/user/hey', { username: 'charlike '})
console.log(ret) // => 'charlike'

Notes

About "on route"

You can customize everything. By default, we call the route handler with single "context" object which contains .route, .pathname, .params and .state properties.

But instead of this you may want to pass more additional arguments to route handler or include only few of these above. To do this you can off the default .on('route') logic and provide a new logic. The listener of route event will be passed with (handler, context, el) signature. Where handler is the route handler function, context is the above context object, and el can be the "previous" returned value of the handler call (it is useful for diffing).

In above API docs have existing example, but let's try it again.

// remove the defafult
app.off('route')

Okey, let's say we want our route handlers to have (params, actions) signature. We can get the first from the "context" object, but what about "actions". Let's think of the route handler as "view", so we want to pass some actions to be done on some scenario.

Tip: This is the perfect place to plug in a virtual or real dom diffing algorithm! You definitely should try to use nanomorph here to see the magic! :)

const actions = {
  hi: (name) => alert('hi ' + name)
}

app.on('route', (handler, context) => {
  return handler(context.params, actions)
})

Now, let's define our simple view with bel, a simple DOM builder using tagged template strings.

const html = require('bel')

app.addRoute('/hello/:name', (params, actions) => {
  return html`<div>
    <h1>Hello ${params.name}</h1>
    <button onclick=${() => actions.hi(params.name)}>Click me to alert you</button>
  </div>`
})

This view just outputs one heading and a button, which when is clicked will say "hi" to different persons, based on the passed url, which in our case will be fired with .navigate method.

const res = app.navigate('/hello/charlike')

console.log(res) // => DOM element
console.log(res.toString())
// =>
// <div>
//   <h1>Hello charlike</h1>
//   <button>Click me to alert you</button>
// </div>

And because .navigate method returns what is returned value from the matched route, we can easy get the rendered page.

About routing

By default we use really simple approach for covering most common and simple cases. It is similar to what we see in Express app's routing, where :name is a placeholder for some param.

But because everything is some simple, small and pluggable, you can create another plugin that provide a different .createRoute method, for example using path-match. There's only few things that you should follow and they can be seen in the source code, it is pretty small and easy to understand.

Related

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Please read the contributing guidelines for advice on opening issues, pull requests, and coding standards.
If you need some help and can spent some cash, feel free to contact me at CodeMentor.io codementor-url too.

In short: If you want to contribute to that project, please follow these things

  1. Please DO NOT edit README.md, CHANGELOG.md and .verb.md files. See "Building docs" section.
  2. Ensure anything is okey by installing the dependencies and run the tests. See "Running tests" section.
  3. Always use npm run commit to commit changes instead of git commit, because it is interactive and user-friendly. It uses commitizen behind the scenes, which follows Conventional Changelog idealogy.
  4. Do NOT bump the version in package.json. For that we use npm run release, which is standard-version and follows Conventional Changelog idealogy.

Thanks a lot! :)

Building docs

Documentation and that readme is generated using verb-generate-readme, which is a verb generator, so you need to install both of them and then run verb command like that

$ npm install verbose/verb#dev verb-generate-readme --global && verb

Please don't edit the README directly. Any changes to the readme must be made in .verb.md.

Running tests

Clone repository and run the following in that cloned directory

$ npm install && npm test

Author

Charlike Mike Reagent

License

Copyright © 2017, Charlike Mike Reagent. Released under the MIT License.


This file was generated by verb-generate-readme, v0.4.3, on March 29, 2017.
Project scaffolded using charlike cli.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation

add - brightgreen fix - yellow remove - red update - orange

#940058c

- add
- fix
- add
- remove
- update


http://www.ongamers.com/articles/top-ten-counter-strike-1-0-to-1-6-players-who-could-have-been-the-greatest-of-all-time/1100-846


bg-best.info - Безплатни домейни от СуперХостинг.БГ bg-best.info е форум, който има за цел да предостави на своите потребители безплатни домейни срещу точки, които се печелят с писане на мнения и теми. Форумът стартира на 13 май 2007 и досега(01 март 2008) има 1241 регистрирани потребители и 104146


http://mywebtrip.wordpress.com/2008/09/23/bg-bestinfo-%D0%B1%D0%B5%D0%B7%D0%BF%D0%BB%D0%B0%D1%82%D0%BD%D0%B8-%D0%B4%D0%BE%D0%BC%D0%B5%D0%B9%D0%BD%D0%B8/: BG-Best.Info е форум в който съм редовен поради длъжността си. Като казах „поради длъжността си“ исках да кажа, че съм глобален модератор и няма как да не съм редовен. В форума съм вече от година и половина близо и вече взе да ми омръзва, но като по навик си влизам и си разглеждам темите с удоволствие. В него можете да вземете безплатни домейни .com/.net./.org/.info от superhosting.bg, като пишете в форума и от самите постове ви се натрупват точки чрез които можете да си поръчате по-горе посочените домейни. Също така търговията с точки е доста добра. Тоест ако не искате домейн, а форума ви харесва, може да се регистрирате просто за да ви правят хедъри, банери, аватари и други услуги срещу точки. Също така можете да релаксирате след дългият работен ден в субфорума „Лафче“, където някой път можете да срещнете и доста излишен спам. Това е от мен!