Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

params #22

Merged
merged 3 commits into from
Apr 7, 2017
Merged

params #22

merged 3 commits into from
Apr 7, 2017

Conversation

refractalize
Copy link
Member

@refractalize refractalize commented Apr 6, 2017

Params

Httpism will render a URL template if the params option is used, the params are interpolated into the URL template, any params left over will form the query string.

httpism.get('http://example.com/users/:user/posts', {
  params: {
    user: 'bob',
    page: 3,
    search: 'lakes'
  }
})

Will become

GET http://example.com/users/bob/posts?page=3&search=lakes

A template contains two forms of parameter, varying on the way special characters are encoded for URLs.

  • :param - uses encodeURIComponent, and is useful for most applications
  • :param* - uses encodeURI and can be used to interpolate paths, such as a/path/to/something without encoding the slash characters.

Any remaining parameters will be encoded in the query string, you can override how the query string is encoded using the qs option.

The template interpolation itself can be overridden with the expandUrl option, and is used as follows:

var url = expandUrl(template, params, querystring)
  • template - the URL template, passed in as the url argument to httpism.get, etc.
  • params - the object containing the parameters to be interpolated.
  • querystring - the qs option, can be used to encode the query string parameters, e.g. querystring.stringify(params).

For example, you could use RFC 6570 templates like this

var urlTemplate = require('url-template')

function expandUrl(url, params) {
  var template = urlTemplate.parse(url)
  return template.expand(params)
}

httpism.get('http://example.com/users/{user}/posts{?page,search}', {
  params: {
    user: 'bob',
    page: 3,
    search: 'lakes'
  },
  expandUrl: expandUrl
})

Or indeed create a new client to use this by default:

var httpism = require('httpsim').client({
  expandUrl: expandUrl
})

httpism.get('http://example.com/users/{user}/posts{?page,search}')

@dereke
Copy link
Member

dereke commented Apr 6, 2017

@refractalize this looks great!

@refractalize refractalize merged commit ac5e810 into master Apr 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants