url-buildr
Author: Hasnain-Haider
Overview: This object assembles URLs and routes
An NPM package:
Quickly assemble routes and urls. Can be used for a variety of purposes like
- Route Generation/Modularization
- API testing
- Webcrawling/scraping
- etc.
API:
Class: URLBuildr
Creates an object to create urls
URLBuildr.create(options)
The preferred method of creating strings. Returns a URLBuildr object, calls the constructor
Parameters
initializer: object|string
, Creates a URLBuildr
Returns: this
e.g. var myUrl = ub.create(myOptions).toString()
{options}
- options.prefix {string} - at the very beginning of the url
- options.pathPrefix {string} - at the very beginning of the path
- options.additions {string[]} - additions to the path, added sequentially
- options.port {integer|string} - port of the url
- options.host {string} - url host
- options.params {string[]|object} - parameters and their values // [key1,val1, key2,val2] OR {key1:val1, key2:val2}
- options.queries: {string[]|object} - queries and the values // (Same format as above)
The url is made in the following format:
(prefix)(host)(:port)(pathPrefix)(additions)
.
URLBuildr.add(paths)
Adds to url path, after the prefix, host, port and pathPrefix
Parameters
paths: ...string|string[]
, Creates an object to create urls
Returns: this
e.g. ub.add('accounts', 'users')
or ub.add(['accounts', 'users'])
URLBuildr.param(params)
Fills in parameters in the url if they are present
Parameters
params: string[]|...string|object
, pass a string array, object, or several strings
Returns: this
e.g.
ub;ub;ub;
URLBuildr.query(query)
Insert query strings at the end of the url
Parameters
query: string[]|..string|object
, pass a string array, object, or several strings
Returns: this
URLBuildr.clear()
reset the Object options()
URLBuildr.toString()
Returns the constructed URL
Returns: string
, urlString
URLBuildr.set(opt)
Assign a value to the given options field
Parameters
opts: object
, set fields in the options object of "this"
Returns: this
e.g. ub.set({host: 3000})
URLBuildr.setOptions(options)
Overwrites the entire options object of "this"
Parameters
options: object
, Object containing configurations for the url
Returns: this
Examples
There are two ways to use this module
- Instantiate the object with an 'options' object
- if this method is used, you MUST pass an object with a defined host to the constructor
- Instantiate with a string
- Some features are disabled in this method
- the URLs are generated with object chaining
The leading and following forward slash(es) are ignored in most cases.
Here's a quick example showing the first way
var ub = ;var urlObj = ub;
When toString() is called the following string is returned: https://thegreatsite.co:65132/accounts/users/54298/cart?showAllPurchases=true
Example producing the same url as above using the chaining method:
var urlObj = ub ;