kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.71k stars 103 forks source link

query/search support? #109

Closed frozenfung closed 7 years ago

frozenfung commented 7 years ago

Hey, team. Really appreciate you guys work on this project.

Without it I can't migrate my existing Rails app into a SPA base on nodeJS. Or I need to try to figure out what the hell react-router is going on, which I think is too complete and brilliant to me, my app is a tiny one.

Now I face a situation that I need to access query/search in the route object.

For example, I have an endpoint http://www.example.com/?foo=bar. Owing to the different query foo=bar or baz=quz I have to set different state into my template. Is it possible we have the parsed query as a default params in context object just like params?

Right now I use this library for parsing in client side, and access with req.query in server side. But I think it maybe cool if we pre-parsed it.

I can come with a PR if you buy this one.

thanks

frenzzy commented 7 years ago
import Router from 'universal-router'
import queryString from 'query-string'

const router = new UniversalRouter({
  path: '/user/:username',
  action(context) {
    console.log(context.path)   // => '/user/jhon'
    console.log(context.params) // => { username: 'jhon' }
    console.log(context.query)  // => { query: 'and', hash: '' }
    console.log(context.hash)   // => '#example'
    return /* ... */
  }
})

// location = 'http://example.com/user/jhon?query=and&hash#example'
router.resolve({
  path: location.pathname,
  query: queryString.parse(location.search), // <=== pass query params here
  hash: location.hash
}).then(render)

Demo: https://jsfiddle.net/frenzzy/g7ymd7ho/

frozenfung commented 7 years ago

@frenzzy Thanks for the demo.